Category: Excel Access


Sub test()
    Dim var         As Variant
    var = List_Files_In_Folder(“C:\”, “*.*”, True)
End Sub
Function List_Files_In_Folder(ByVal strFolderPath As String, Optional strFilter As String = “*.*”, Optional bolFullPath As Boolean = False) As Variant
    Dim strTemp                 As String
    Dim strFile                 As String
    Const strDelimeter          As String = “|”
    strTemp = Dir(strFolderPath & strFilter)
    If bolFullPath Then strTemp = strFolderPath & strTemp
    If strTemp = “” Then
        List_Files_In_Folder = False
        Exit Function
    End If
    Do
        strFile = Dir
        If strFile = “” Then Exit Do
        If bolFullPath Then strFile = strFolderPath & strFile
        strTemp = strTemp & strDelimeter & strFile
     Loop
    List_Files_In_Folder = Split(strTemp, strDelimeter)
End Function
Sub a()
Dim r As Range
Set r = Intersect(ActiveSheet.UsedRange.SpecialCells(xlCellTypeAllValidation), ActiveSheet.UsedRange.SpecialCells(xlCellTypeVisible))
If Intersect(ActiveCell, r) Is Nothing Then
    MsgBox “Cell has no validation”
Else
    MsgBox “Cell has validation”
End If
End Sub
Option Explicit
Option Compare Text
Private Const mc_strModuleName       As String = “modGetUNCPath”
Private Declare Function WNetGetConnection Lib “mpr.dll” Alias “WNetGetConnectionA” (ByVal lpszLocalName As String, ByVal lpszRemoteName As String, cbRemoteName As Long) As Long
‘Purpose   :    Returns the UNC Path given a path
‘Inputs    :    sPathName           The path to convert
‘Outputs   :    The UNC path of sPathName
‘Notes     :    Requires NT/2000
‘Revisions :
Function ConvertToUNC(sPathName As String) As String
    Dim szValue As String, szValueName As String, sUNCName As String
    Dim lErrCode As Long, lEndBuffer As Long
    Const lLenUNC As Long = 520
    ‘Return values for WNetGetConnection
    Const NO_ERROR As Long = 0
    Const ERROR_NOT_CONNECTED As Long = 2250
    Const ERROR_BAD_DEVICE = 1200&
    Const ERROR_MORE_DATA = 234
    Const ERROR_CONNECTION_UNAVAIL = 1201&
    Const ERROR_NO_NETWORK = 1222&
    Const ERROR_EXTENDED_ERROR = 1208&
    Const ERROR_NO_NET_OR_BAD_PATH = 1203&
    ‘Verify whether the disk is connected to the network
    If Mid$(sPathName, 2, 1) = “:” Then
        sUNCName = String$(lLenUNC, 0)
        lErrCode = WNetGetConnection(Left$(sPathName, 2), sUNCName, lLenUNC)
        lEndBuffer = InStr(sUNCName, vbNullChar) – 1
        ‘Can ignore the errors below (will still return the correct UNC)
        If lEndBuffer > 0 And (lErrCode = NO_ERROR Or lErrCode = ERROR_CONNECTION_UNAVAIL Or lErrCode = ERROR_NOT_CONNECTED) Then
            ‘Success
            sUNCName = Trim$(Left$(sUNCName, InStr(sUNCName, vbNullChar) – 1))
            ConvertToUNC = sUNCName & Mid$(sPathName, 3)
        Else
            ‘Error, return original path
            ConvertToUNC = sPathName
        End If
    Else
        ‘Already a UNC Path
        ConvertToUNC = sPathName
    End If
End Function
Sub test()
    MsgBox getGoogleTranslation(“Lion”, “english”, “hindi”)
End Sub
Public Function getGoogleTranslation(ByVal strSource As String, ByVal strSourceLang As String, ByVal strDestLang As String) As String
    Dim strURL                      As String
    Dim strRes                      As String
    Dim varArrLanguage()            As Variant
    Dim varArrGoogleLanguage()      As Variant
    Dim lngLangVal                  As Long
    varArrLanguage = Array(“AFRIKAANS”, “ALBANIAN”, “ARABIC”, “BELARUSIAN”, “BULGARIAN”, _
                           “CATALAN”, “CHINESE”, “CHINESE SIMPLIFIED”, “CHINESE TRADITIONAL”, _
                           “CROATIAN”, “CZECH”, “DANISH”, “DUTCH”, “ENGLISH”, “ESTONIAN”, _
                           “FILIPINO”, “FINNISH”, “FRENCH”, “GALICIAN”, “GERMAN”, “GREEK”, _
                           “HEBREW”, “HINDI”, “HUNGARIAN”, “ICELANDIC”, “INDONESIAN”, “IRISH”, _
                           “ITALIAN”, “JAPANESE”, “KOREAN”, “LATVIAN”, “LITHUANIAN”, “MACEDONIAN”, _
                           “MALAY”, “MALTESE”, “NORWEGIAN”, “PERSIAN”, “POLISH”, “PORTUGUESE”, _
                           “ROMANIAN”, “RUSSIAN”, “SERBIAN”, “SLOVAK”, “SLOVENIAN”, “SPANISH”, _
                           “SWAHILI”, “SWEDISH”, “TAGALOG”, “THAI”, “TURKISH”, “UKRAINIAN”, _
                           “VIETNAMESE”, “WELSH”, “YIDDISH”)
    varArrLanguage = Application.Transpose(Application.Transpose(varArrLanguage))
    varArrGoogleLanguage = Array(“af”, “sq”, “ar”, “be”, “bg”, _
                                 “ca”, “zh”, “zh-CN”, “zh-TW”, _
                                 “hr”, “cs”, “da”, “nl”, “en”, “et”, _
                                 “tl”, “fi”, “fr”, “gl”, “de”, “el”, _
                                 “iw”, “hi”, “hu”, “is”, “id”, “ga”, _
                                 “it”, “ja”, “ko”, “lv”, “lt”, “mk”, _
                                 “ms”, “mt”, “no”, “fa”, “pl”, “pt-PT”, _
                                 “ro”, “ru”, “sr”, “sk”, “sl”, “es”, _
                                 “sw”, “sv”, “tl”, “th”, “tr”, “uk”, _
                                 “vi”, “cy”, “yi”)
    varArrGoogleLanguage = Application.Transpose(Application.Transpose(varArrGoogleLanguage))
    lngLangVal = 0
    On Error Resume Next
    lngLangVal = WorksheetFunction.Match(UCase(Trim(strSourceLang)), varArrLanguage, 0)
    On Error GoTo 0: Err.Clear
    If lngLangVal > 0 Then
        strSourceLang = varArrGoogleLanguage(lngLangVal)
    Else
        strSourceLang = vbNullString
    End If
    lngLangVal = 0
    On Error Resume Next
    lngLangVal = WorksheetFunction.Match(LCase(Trim(strDestLang)), varArrLanguage, 0)
    On Error GoTo 0: Err.Clear
    If lngLangVal > 0 Then
        strDestLang = varArrGoogleLanguage(lngLangVal)
    Else
        strDestLang = vbNullString
    End If
    If strSourceLang <> vbNullString Or strDestLang <> vbNullString Then
        strURL = strURL & Replace(strSource, ” “, “%20”)
        strURL = strURL & “&hl=en&sl=” & strSourceLang
        strURL = strURL & “&tl=” & strDestLang & “&multires=1&pc=0&rom=1&sc=1”
        With CreateObject(“msxml2.xmlhttp”)
            .Open “get”, strURL, False
            .send
            strRes = .responseText
        End With
        getGoogleTranslation = Replace(Replace(Split(strRes, “,”)(0), “[“, “”), “”””, “”)
    Else
        getGoogleTranslation = vbNullString
    End If
End Function

Enum QrySchema
QrySchemaProcedures = 16
QrySchemaTables = 20
QrySchemaViews = 23
End Enum

Function ModifyQryDef(ByVal strDBFullPath As String, ByVal strQryName As String, ByVal strNewQryDef As String, _
ByVal strRplwhat As String, ByVal strRplwith As String, _
ByVal QrySchemaType As QrySchema, Optional blnReplace As Boolean = False) As String

Dim objCmd                  As Object
Dim objCat                  As Object
Dim objCmdType              As Object

On Error GoTo XitPoint

‘Creating ADOX Object
Set objCat = CreateObject(“ADOX.Catalog”)
objCat.activeconnection = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source= ” & strDBFullPath

‘Checking query type
Select Case QrySchemaType
Case 16 ‘Procedures
Set objCmdType = objCat.Procedures(strQryName)
Case 20 ‘Tables
Set objCmdType = objCat.Tables(strQryName)
Case 23 ‘Views
Set objCmdType = objCat.Views(strQryName)
End Select

‘Getting commond object
Set objCmd = objCmdType.Command

‘If need to replace query
If blnReplace Then
If strNewQryDef = “” Then strNewQryDef = objCmd.CommandText
strNewQryDef = Replace(strNewQryDef, strRplwhat, strRplwith)
End If

‘Modifying query
objCmd.CommandText = strNewQryDef
Set objCmdType.Command = objCmd

‘MsgBox “Query has been modified !”
ModifyQryDef = “Successfull”

XitPoint:
If Err.Number <> 0 Then
MsgBox “Err. Number:- ” & Err.Number & vbLf & vbLf & “Err. Description:- ” & Err.Description, vbCritical, “Database”
ModifyQryDef = “Unsuccessfull”
Err.Clear
On Error GoTo 0
End If

objCat.activeconnection.Close

Set objCmdType = Nothing
Set objCmd = Nothing
Set objCat = Nothing

End Function

Function ChangeColumnName(ByVal strDBFullPath As String, ByVal strTabName As String, _
ByVal strOldColName As String, ByVal strNewColName As String) As String

Dim objCat                  As Object
Dim objTbl                  As Object
Dim objCol                  As Object
Const strMsgBoxTitle        As String = “Change Column Name”

On Error GoTo XitPoint

Set objCat = CreateObject(“ADOX.Catalog”)
Set objTbl = CreateObject(“ADOX.Table”)

objCat.activeconnection = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source= ” & strDBFullPath
Set objTbl = objCat.Tables(strTabName)
objTbl.Columns(strOldColName).Name = strNewColName
objCat.activeconnection.Close
ChangeColumnName = “Successfull”
Exit Function

XitPoint:
If Err.Number = 3265 Then
MsgBox “Given table\column is not found.” & vbLf & “Please check if the given table\column exist.”, vbCritical, strMsgBoxTitle
ElseIf Err.Number <> 3265 And Err.Number <> 0 Then
MsgBox “Error Number:- ” & Err.Number & vbLf & “Error Description:- ” & Err.Description, vbCritical, strMsgBoxTitle
End If
Err.Clear
On Error GoTo 0
ChangeColumnName = “Unsuccessfull”

End Function

Option Explicit
Option Compare Text
Private adoConn              As Object
Private adoRset              As Object
Private Const mc_strModuleName      As String = “modExportExcelDataToAccess”
Private Const strMsgBoxTitle        As String = “Uploader”
Sub test()
    With ThisWorkbook.Worksheets(“Master”)
        Debug.Print .Range(Selection, .Cells(.Cells(.Rows.Count, Selection.Column).End(xlUp).Row, .Cells(Selection.Row, .Columns.Count).End(xlToLeft).Column)).Address
    End With
    ‘Call ExportDataIntoAccess( _
                                db_FullPath:=ThisWorkbook.Path & Application.PathSeparator & strDbName, _
                                db_tblName:=”Test” & CLng(Timer), _
                                xl_FileFullPath:=ThisWorkbook.FullName, _
                                xl_SheetName:=”Sheet1″, _
                                xl_DataRange:=”$A$1:$E$200000″, _
                                xl_HeaderYes:=True, _
                                xl_DataStartCell:=false, _
                                blnDelTableExistingData:=True)
End Sub
Sub ExportDataIntoAccess( _
                            ByVal db_FullPath As String, _
                            ByVal db_tblName As String, _
                            ByVal xl_FileFullPath As String, _
                            ByVal xl_SheetName As String, _
                            ByVal xl_DataRange As String, _
                            ByVal xl_HeaderYes As Boolean, _
                            Optional xl_DataStartCell As Boolean = False, _
                            Optional blnDelTableExistingData As Boolean = False, _
                            Optional blnShowMessage As Boolean = False)
    ‘// Purpose     : Export data from the Excel Workbook into Access Table Row By Row
    ‘// Author      : Lalit Mohan
    ‘// Created On  : 06-Nov-2012
    Dim wbkWorkBook         As Workbook
    Dim wksWorkSheet        As Worksheet
    Dim rngFirstCell        As Range
    Dim rngData             As Range
    Dim varData             As Variant
    Dim dataFlds()          As Variant
    Dim dataFld()           As Variant
    Dim varFound            As Variant
    Dim lngLoopD            As Long
    Dim lngLoopA            As Long
    Dim lngLoop             As Long
    Dim lngFldsCount        As Long
    Dim lngLastCol          As Long
    Dim lngLastRow          As Long
    Dim lngCounter          As Long
    Dim lngScreenUp         As Long
    Dim lngCalc             As Long
    Dim strSql              As String
    Dim strTemp             As String
    Dim strAddress          As String
    Dim dblSum              As Double
    Dim dtTime              As Date
    dtTime = Time
    Const DataTypeNumeric   As String = “Single”
    Const DataTypeString    As String = “varchar(255)”
    Const DataTypeDateTime  As String = “DateTime”
    ‘Setting Table Name
    If Left(db_tblName, 1) <> “[” Then
        db_tblName = “[” & db_tblName
    End If
    If Right(db_tblName, 1) <> “]” Then
        db_tblName = db_tblName & “]”
    End If
    ‘Checking file path is correct.
    If Not IsFileExists(xl_FileFullPath) Then Exit Sub
    ‘Disabling Application Level Events
    With Application
        .EnableEvents = 0
        lngCalc = .Calculation
        lngScreenUp = .ScreenUpdating
        ‘.ScreenUpdating = 0
        .DisplayAlerts = 0
        .Calculation = xlCalculationManual
    End With
    ‘Checking if given file and sheet is available or not
    On Error Resume Next
    If Not IsFileOpen(xl_FileFullPath) Then
        Set wbkWorkBook = Workbooks.Open(xl_FileFullPath)
    ElseIf LCase(ThisWorkbook.FullName) = LCase(xl_FileFullPath) Then
        Set wbkWorkBook = ThisWorkbook
    Else
        If IsFileOpen(xl_FileFullPath) Then
            MsgBox “File is already open. Please save file and close it first to upload data.”, vbCritical, strMsgBoxTitle
            GoTo QuickExit
        Else
            Set wbkWorkBook = Workbooks.Open(xl_FileFullPath)
        End If
    End If
    Set wksWorkSheet = wbkWorkBook.Worksheets(CStr(xl_SheetName))
    ‘Error handling
    If Err.Number <> 0 Then
        MsgBox “Worksheet ‘” & xl_SheetName & ” doesn’t exists”, vbInformation
        Err.Clear: On Error GoTo 0
        GoTo QuickExit
    End If
    Call OpenDB(db_FullPath)
    With wksWorkSheet
        ‘Data Range
        If xl_DataStartCell Then
            ‘Set rngData = .Range(xl_DataRange).Resize(.Cells(.Rows.Count, .Range(xl_DataRange).Column).End(xlUp).Row, .Range(xl_DataRange, .Cells(.Range(xl_DataRange).Row, .Columns.Count).End(xlToLeft)).Columns.Count)
            Set rngData = .Range(.Range(xl_DataRange), .Cells(.Cells(.Rows.Count, .Range(xl_DataRange).Column).End(xlUp).Row, .Cells(.Range(xl_DataRange).Row, .Columns.Count).End(xlToLeft).Column))
        Else
            Set rngData = .Range(xl_DataRange)
        End If
        ‘checking for header if available
        If xl_HeaderYes Then
            If blnTableExistsInDB(db_tblName) Then adoConn.Execute “Drop table” & db_tblName
            If rngData.Resize(1).Columns.Count > 1 Then
                dataFlds = Application.Transpose(Application.Transpose(rngData.Resize(1).Value))
            ElseIf rngData.Resize(1).Columns.Count = 1 Then
                ReDim dataFlds(1 To 1)
                dataFlds(1) = rngData.Resize(1).Value
            End If
        Else
            adoRset.Open “Select * From ” & db_tblName & ” Where 1=2″, adoConn, 3, 3
            ReDim dataFld(1 To adoRset.fields.Count)
            For lngLoop = 0 To adoRset.fields.Count – 1
                Select Case adoRset.fields(lngLoop).Type
                    Case 202 ‘adVarWChar
                        dataFld(lngLoop + 1) = 202 ‘advarWChar
                    Case 3 ‘Long Integer
                        dataFld(lngLoop + 1) = 3 ‘adSingle
                    Case 4 ‘adSingle
                        dataFld(lngLoop + 1) = 4 ‘adSingle
                    Case 5 ‘adDouble
                        dataFld(lngLoop + 1) = 5 ‘adDouble
                    Case 7 ‘adDate
                        dataFld(lngLoop + 1) = 7 ‘adDate
                End Select
            Next lngLoop
        End If
        varData = rngData
    End With
    If LCase(ThisWorkbook.FullName) <> LCase(xl_FileFullPath) Then wbkWorkBook.Close (0)
    On Error GoTo 0
    ‘Checking if table is already exist  or not.
    If Not blnTableExistsInDB(CStr(db_tblName)) Then
        ‘Creating table
        If xl_HeaderYes Then
            If IsArray(varData) And IsArray(dataFlds) Then
                strTemp = “Create Table ” & CStr(db_tblName) & vbLf & “(“
                ReDim dataFld(1 To UBound(dataFlds, 1))
                For lngLoopD = 1 To UBound(dataFlds, 1)
                    If IsNumeric(varData(2, lngLoopD)) And Len(varData(2, lngLoopD)) Then
                        strTemp = strTemp & vbLf & IIf(lngLoopD = 1, “[” & dataFlds(lngLoopD) & “]”, “,[” & dataFlds(lngLoopD) & “]”) & ” ” & DataTypeNumeric
                        dataFld(lngLoopD) = 5 ‘adDouble
                    ElseIf IsDate(varData(2, lngLoopD)) Then
                        strTemp = strTemp & vbLf & IIf(lngLoopD = 1, “[” & dataFlds(lngLoopD) & “]”, “,[” & dataFlds(lngLoopD) & “]”) & ” ” & DataTypeDateTime
                        dataFld(lngLoopD) = 7 ‘adDate
                    Else
                        strTemp = strTemp & vbLf & IIf(lngLoopD = 1, “[” & dataFlds(lngLoopD) & “]”, “,[” & dataFlds(lngLoopD) & “]”) & ” ” & DataTypeString
                        dataFld(lngLoopD) = 202 ‘advarWChar
                    End If
                Next lngLoopD
                strTemp = strTemp & vbLf & “)”
                adoConn.Execute Replace(strTemp, “””, “Null”)
            End If
        Else
            If IsArray(varData) Then
                strTemp = “Create Table ” & CStr(db_tblName) & vbLf & “(“
                For lngLoopD = 1 To UBound(varData, 2)
                    If IsNumeric(varData(2, lngLoopD)) And Len(varData(2, lngLoopD)) Then
                        strTemp = strTemp & vbLf & IIf(lngLoopD = 1, “[Field” & lngLoopD & “]”, “,[Field” & lngLoopD & “]”) & ” ” & DataTypeNumeric
                    ElseIf IsDate(varData(2, lngLoopD)) Then
                        strTemp = strTemp & vbLf & IIf(lngLoopD = 1, “[Field” & lngLoopD & “]”, “,[Field” & lngLoopD & “]”) & ” ” & DataTypeNumeric
                    Else
                        strTemp = strTemp & vbLf & IIf(lngLoopD = 1, “[Field” & lngLoopD & “]”, “,[Field” & lngLoopD & “]”) & ” ” & DataTypeString
                    End If
                Next lngLoopD
                strTemp = strTemp & vbLf & “)”
                adoConn.Execute Replace(strTemp, “””, “Null”)
            End If
        End If
    Else
        ‘Delete existing data from the table.
        If blnDelTableExistingData Then
            strSql = “Delete * FROM ” & CStr(db_tblName)
            adoConn.Execute strSql
        End If
    End If
    ‘Inserting data into the table row by row.
    On Error GoTo EarlyExit
    If IsArray(varData) Then
        For lngLoopD = LBound(varData) + 1 To UBound(varData, 1)
            strTemp = “INSERT INTO ” & CStr(db_tblName) & ” VALUES (“
            For lngLoopA = 1 To UBound(dataFld)
                Select Case dataFld(lngLoopA)
                    Case 3, 4, 5 ‘If datafld(lngLoopA) = 5 Or datafld(lngLoopA) = 4 Then ‘adDouble ‘adSigle
                        If Not IsEmpty(varData(lngLoopD, lngLoopA)) Then
                            strTemp = strTemp & vbLf & Trim(IIf(lngLoopA = 1, varData(lngLoopD, lngLoopA), “,” & varData(lngLoopD, lngLoopA)))
                        ElseIf IsEmpty(varData(lngLoopD, lngLoopA)) Then
                            strTemp = strTemp & vbLf & IIf(lngLoopA = 1, “NULL”, “,NULL”)
                        End If
                    Case 7 ‘ElseIf datafld(lngLoopA) = 7 Then ‘adDate
                        varData(lngLoopD, lngLoopA) = Replace(varData(lngLoopD, lngLoopA), “#”, “”)
                        varData(lngLoopD, lngLoopA) = Evaluate(“=VALUE(“”” & varData(lngLoopD, lngLoopA) & “””)”)
                        strTemp = strTemp & vbLf & Trim(IIf(lngLoopA = 1, varData(lngLoopD, lngLoopA), “,” & varData(lngLoopD, lngLoopA)))
                    Case 202 ‘f datafld(lngLoopA) = 202 Then ‘advarWChar
                        varData(lngLoopD, lngLoopA) = Trim(Replace(varData(lngLoopD, lngLoopA), “‘”, “””))
                        varData(lngLoopD, lngLoopA) = Trim(Replace(varData(lngLoopD, lngLoopA), “”””, “”””””))
                        strTemp = strTemp & vbLf & Trim(IIf(lngLoopA = 1, “‘” & varData(lngLoopD, lngLoopA) & “‘”, “,'” & varData(lngLoopD, lngLoopA) & “‘”))
                End Select
                ‘Debug.Print strTemp
            Next lngLoopA
            strTemp = strTemp & “)”
            ‘Debug.Print “ROW: ” & lngLoopD ‘  & “:” & strTemp
            StatusBar lngLoopD & ” Out Of ” & UBound(varData) – 1 & “…”  ‘Records inserted into ” & db_tblName & ” …”
            adoConn.Execute Replace(strTemp, “””, “Null”)
        Next lngLoopD
        StatusBar lngLoopD & ” Records are inserted successfully.” ‘ & vbLf & ” Process Started at ” & dtTime & ” and Finished at ” & Time)
        If blnShowMessage Then MsgBox lngLoopD & ” Records are inserted successfully.” ‘ & vbLf & ” Process Started at ” & dtTime & ” and Finished at ” & Time, vbInformation, strMsgBoxTitle
        Call StatusBar(, False)
    End If
EarlyExit:
    If Err.Number <> 0 Then
        If blnShowMessage Then MsgBox “Error #:” & Err.Number & vbLf & Err.Description
        Err.Clear: On Error GoTo 0
        Stop
        End
    Else
        Call StatusBar(“”, False)
    End If
    Erase varData
    dblSum = Empty
    Erase dataFlds
    Erase dataFld
QuickExit:
    With Application
        .EnableEvents = 1
        .ScreenUpdating = lngScreenUp
        .DisplayAlerts = 1
        .Calculation = lngCalc
    End With
    Call CloseDB
    Set wbkWorkBook = Nothing
    Set wksWorkSheet = Nothing
    Set rngFirstCell = Nothing
    Set rngData = Nothing
    varData = Empty
    Erase dataFlds
    Erase dataFld
    varFound = Empty
    lngLoopD = Empty
    lngLoopA = Empty
    lngLoop = Empty
    lngFldsCount = Empty
    lngLastCol = Empty
    lngLastRow = Empty
    lngCounter = Empty
    lngScreenUp = Empty
    lngCalc = Empty
    strSql = vbNullString
    strTemp = vbNullString
    strAddress = vbNullString
    dblSum = Empty
    dtTime = Empty
End Sub
Private Function IsFileExists(ByVal FullFileName As String) As Boolean
    IsFileExists = False
    On Error Resume Next
    IsFileExists = CBool(Len(Dir(FullFileName)))
End Function
Private Sub OpenDB(ByVal strDBPath As String)
    Set adoConn = CreateObject(“ADODB.Connection”)
    Set adoRset = CreateObject(“ADODB.Recordset”)
    adoConn.Open “Provider=Microsoft.Jet.OLEDB.4.0;data source=” & CStr(strDBPath) & “;”
End Sub
Private Sub CloseDB()
    On Error Resume Next
    If adoRset.State <> 0 Then adoRset.Close
    If adoConn.State <> 0 Then adoConn.Close
    On Error GoTo 0: Err.Clear
End Sub
Private Function blnTableExistsInDB(strTableName As String) As Boolean
    Dim rst         As Object
    Dim strTbl      As String
    strTbl = strTableName
    Set rst = adoConn.OpenSchema(20) ‘adSchemaTables
    If Left(strTbl, 1) = “[” And Right(strTbl, 1) = “]” Then
        strTbl = Mid(strTbl, 2, Len(strTbl) – 2)
    End If
    rst.Filter = “TABLE_TYPE=’TABLE’ and TABLE_NAME='” & strTbl & “‘”
    On Error Resume Next
    blnTableExistsInDB = (UCase(rst.fields(“TABLE_NAME”).Value) = UCase(strTbl))
    On Error GoTo 0
    If Err.Number <> 0 Then blnTableExistsInDB = False
    Set rst = Nothing
    strTbl = vbNullString
End Function
Private Function IsFileOpen(ByVal FileName As String)
    Dim iFilenum As Long
    Dim iErr As Long
    On Error Resume Next
    iFilenum = FreeFile()
    Open FileName For Input Lock Read As #iFilenum
    Close iFilenum
    iErr = Err
    On Error GoTo 0
    Select Case iErr
    Case 0:    IsFileOpen = False
    Case 70:   IsFileOpen = True
    Case Else: Error iErr
    End Select
    iFilenum = Empty
    iErr = Empty
End Function
Private Sub StatusBar(Optional strMsg As String = vbNullString, Optional blnShow As Boolean = True)
    DoEvents
    If Not blnShow Then Application.StatusBar = blnShow: Exit Sub
    Application.StatusBar = strMsg
End Sub
Option Explicit
Public Const gc_strDataBaseName             As String = “BrandTrendDatabase.mdb”
Public lngRecEff                            As Long
Public blnUseVBScript                       As Boolean
Public g_objConnection                      As Object
Public g_objRecordSet                       As Object
Public g_strDBPath                          As String
Public Enum QrySchema
    QrySchemaProcedures = 16
    QrySchemaTables = 20
    QrySchemaViews = 23
End Enum
Function GetDBPath() As String
    ‘GetDBPath = g_strDBPath & Application.PathSeparator & gc_strDataBaseName
    ‘GetDBPath = Environ(“temp”) & “\BSN_Temp\” & gc_strDataBaseName
    GetDBPath = ThisWorkbook.Path & Application.PathSeparator & gc_strDataBaseName
    ‘GetDBPath = ThisWorkbook.CustomDocumentProperties(“DatabasePath”).Value
    ‘GetDBPath = “Z:\Graham_BT\Business Intelligence – Europe\P – 20017 Italy Sales report\WIP\SalesPerformanceDB – Copy.mdb”
End Function
Function blnConnectDatabase(strPath As String, strDBPass As String) As Boolean
    Set g_objConnection = CreateObject(“ADODB.Connection”)
    On Error GoTo ErrH
    g_objConnection.Open “Provider=Microsoft.Jet.OLEDB.4.0; Data Source=” & _
        strPath & “;Jet OLEDB:Database Password=” & strDBPass & “;”
    On Error GoTo 0
    blnConnectDatabase = True
    GoTo ExitH
ErrH:
    blnConnectDatabase = False
    Set g_objConnection = Nothing
ExitH:
    Application.StatusBar = False
End Function
Function blnTableExistsInDB(strTableName As String) As Boolean
    Dim rst         As Object
    Dim strTbl      As String
    strTbl = strTableName
    Call blnConnectDB
    Set rst = CreateObject(“ADODB.Recordset”)
    Set rst = g_objConnection.OpenSchema(20) ‘adSchemaTables
    If Left(strTbl, 1) = “[” And Right(strTbl, 1) = “]” Then
        strTbl = Mid(strTbl, 2, Len(strTbl) – 2)
    End If
    rst.Filter = “TABLE_TYPE=’TABLE’ and TABLE_NAME='” & strTbl & “‘”
    On Error Resume Next
    blnTableExistsInDB = (UCase(rst.fields(“TABLE_NAME”).Value) = UCase(strTbl))
    On Error GoTo 0
    If Err.Number <> 0 Then blnTableExistsInDB = False
    Set rst = Nothing
End Function
Function blnFieldExistsInTable(ByVal strTableName As String, ByVal strFieldName As String) As Boolean
    Dim rst         As Object
    Dim strTbl      As String
    strTbl = strTableName
    Call blnConnectDB
    Set rst = CreateObject(“ADODB.Recordset”)
    Set rst = g_objConnection.OpenSchema(4) ‘adSchemaColumns
    If Left(strTbl, 1) = “[” And Right(strTbl, 1) = “]” Then
        strTbl = Mid(strTbl, 2, Len(strTbl) – 2)
    End If
    rst.Filter = “TABLE_NAME = ‘” & strTableName & “‘ and COLUMN_NAME='” & strFieldName & “‘”
    On Error Resume Next
    blnFieldExistsInTable = (UCase(rst.fields(“COLUMN_NAME”).Value) = UCase(strFieldName))
    On Error GoTo 0
    If Err.Number <> 0 Then blnFieldExistsInTable = False
    Set rst = Nothing
End Function
Function blnProcExistsInDB(strProcName As String) As Boolean
    Dim rst         As Object
    Dim strProc      As String
    strProc = strProcName
    Call blnConnectDB
    Set rst = CreateObject(“ADODB.Recordset”)
    Set rst = g_objConnection.OpenSchema(16) ‘adSchemaProcedures
    If Left(strProc, 1) = “[” And Right(strProc, 1) = “]” Then
        strProc = Mid(strProc, 2, Len(strProc) – 2)
    End If
    rst.Filter = “PROCEDURE_NAME='” & strProc & “‘”
    On Error Resume Next
    blnProcExistsInDB = (UCase(rst.fields(“PROCEDURE_NAME”).Value) = UCase(strProc))
    On Error GoTo 0
    If Err.Number <> 0 Then blnProcExistsInDB = False
    Set rst = Nothing
End Function
Sub ExecuteDBQuery(strQuery As String, Optional rngTarget As Range, Optional blnHeader As Boolean, Optional blnClient As Boolean = False)
    Dim intColIndex                 As Integer
    Dim lngRowOffset                As Long
    ‘On Error GoTo ErrH
    Call blnConnectDB
    Set g_objRecordSet = Nothing
    Set g_objRecordSet = OpenRecordSet(strQuery, blnClient)
    DoEvents
    If g_objRecordSet Is Nothing Then Exit Sub
    With g_objRecordSet
        If Not rngTarget Is Nothing Then
            Set rngTarget = rngTarget.Cells(1, 1)
        End If
        If Not rngTarget Is Nothing Then
            If blnHeader = True Then
                For intColIndex = 0 To .fields.Count – 1 ‘field names
                    rngTarget.Cells(1, intColIndex + 1).NumberFormat = “@”
                    rngTarget.Cells(1, intColIndex + 1).Value = .fields(intColIndex).Name
                    rngTarget.Cells(1, intColIndex + 1).Font.Bold = True
                Next intColIndex
                lngRowOffset = 1
            Else  ‘Without field names
                lngRowOffset = 0
            End If
            If Application.Version < 12 And .RecordCount + rngTarget.Cells(lngRowOffset + 1, 1).Row > 65535 Then
                MsgBox “Records upto row number 65535 can be accommodated. Rest will be ignored.”, vbInformation, “Database”
            ElseIf Application.Version >= 12 And .RecordCount + rngTarget.Cells(lngRowOffset + 1, 1).Row > 1048576 Then
                MsgBox “Records upto row number 1048576 can be accommodated. Rest will be ignored.”, vbInformation, “Database”
            End If
            rngTarget.Cells(lngRowOffset + 1, 1).CopyFromRecordset g_objRecordSet ‘ the recordset data
        End If
    End With
ErrH:
    If Err.Number <> 0 Then
        ‘MsgBox Err.Description, vbCritical, “Error”
        ‘MsgBox “Database Query Error”
    End If
End Sub
Sub DropTable(ParamArray strTableName() As Variant)
    Dim x As Integer
    For x = LBound(strTableName) To UBound(strTableName)
        If blnTableExistsInDB(CStr(strTableName(x))) = True Then
            Call ExecuteDBQuery(“Drop Table [” & Replace(Replace(CStr(strTableName(x)), “[“, “”), “]”, “”) & “]”)
        End If
    Next x
End Sub
Sub DropField(ByVal strTblName As String, ParamArray strColumnName() As Variant)
    Dim x As Integer
    For x = LBound(strColumnName) To UBound(strColumnName)
        If blnFieldExistsInTable(strTblName, CStr(strColumnName(x))) = True Then
            Call ExecuteDBQuery(“ALTER TABLE [” & Replace(Replace(CStr(strTblName), “[“, “”), “]”, “”) & “] DROP COLUMN [” & strColumnName(x) & “]”)
        End If
    Next x
End Sub
Sub DropProcedure(ParamArray strProcName() As Variant)
    Dim x As Integer
    For x = LBound(strProcName) To UBound(strProcName)
        If blnProcExistsInDB(CStr(strProcName(x))) = True Then
            Call ExecuteDBQuery(“Drop PROCEDURE [” & CStr(strProcName(x)) & “]”)
        End If
    Next x
End Sub
Function blnConnectDB() As Boolean
    Dim blnCon          As Boolean
    blnCon = True
    If g_objConnection Is Nothing Then
        blnCon = blnConnectDatabase(GetDBPath, “gskbt”)
    ElseIf Not g_objConnection.State = 1 Then
        blnCon = blnConnectDatabase(GetDBPath, “gskbt”)
    End If
    blnConnectDB = blnCon
End Function
Sub CompactDB()
    Dim strRes As String
    Application.StatusBar = “Compacting database…”
    strRes = DatabaseCompact(GetDBPath)
    If strRes = vbNullString Then
        ‘MsgBox “Succeeded in compacting database …”, vbInformation
        Application.StatusBar = “Succeeded in compacting database …”
    Else
        ‘MsgBox strRes & ” Unable to clean database …”
        Application.StatusBar = strRes & ” Unable to clean database …”
    End If
End Sub
Function DatabaseCompact(strDBPath As String, Optional strDBPass As String = “”) As String
On Error GoTo ErrFailed
    ‘Delete the existing temp database
    If Len(Dir$(strDBPath & “.tmp”)) Then
        VBA.Kill strDBPath & “.tmp”
    End If
    CloseDB
    With CreateObject(“JRO.JetEngine”)
        If strDBPass = “” Then ‘DB without password
            .CompactDatabase “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” & strDBPath, “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” & strDBPath & “.tmp;Jet OLEDB:Encrypt Database=True”
        Else             ‘Password protected db
            .CompactDatabase “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” & strDBPath & “;Jet OLEDB:Database Password=” & strDBPass, “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” & strDBPath & “.tmp;Jet OLEDB:Encrypt Database=True;Jet OLEDB:Database Password=” & strDBPass
        End If
    End With
On Error GoTo 0
    VBA.Kill strDBPath ‘Delete the existing database
    Name strDBPath & “.tmp” As strDBPath ‘Rename the compacted database
ErrFailed:
    If Err.Number <> 0 Then
        DatabaseCompact = Err.Description
    Else
        DatabaseCompact = vbNullString
    End If
End Function
Function SetRecordSet(Optional blnClient As Boolean = False) As Object
    Dim objg_objRecordSet     As Object
    Set objg_objRecordSet = CreateObject(“ADODB.Recordset”)
    With objg_objRecordSet
        If blnClient = True Then
            .CursorLocation = 3 ‘adUseClient
        End If
    End With
    Set SetRecordSet = objg_objRecordSet
    Set objg_objRecordSet = Nothing
End Function
Public Function OpenRecordSet(ByVal strSql As String, Optional blnClient As Boolean = False) As Object
    Dim objg_objRecordSet       As Object
    Dim bolRecordset            As Boolean
    Set objg_objRecordSet = Nothing
    If Not LCase(strSql) Like “update*” And Not LCase(strSql) Like “delete*” And _
        Not LCase(strSql) Like “alter*” And Not LCase(strSql) Like “drop*” And _
        Not LCase(strSql) Like “create*” And Not LCase(strSql) Like “* into *” And _
        Not LCase(strSql) Like “insert*” Then
        bolRecordset = True
    Else
        bolRecordset = False
    End If
    If bolRecordset Then
        Set objg_objRecordSet = CreateObject(“ADODB.Recordset”)
        With objg_objRecordSet
            If blnClient = True Then
                .CursorLocation = 3 ‘adUseClient
                ‘.Open strSQL, g_objConnection, adOpenForwardOnly, adLockReadOnly, adCmdText
                .Open strSql, g_objConnection, 0, 1, 1
                If .RecordCount <> 0 Then .movefirst
                .ActiveConnection = Nothing
            Else
                ‘.Open strSQL, g_objConnection, adOpenStatic, adLockOptimistic, adCmdText
                .Open strSql, g_objConnection, 3, 3, 1
                If objg_objRecordSet.State = 1 Then
                    If .EOF = False And .BOF = False Then .movefirst
                End If
            End If
        End With
        Set OpenRecordSet = objg_objRecordSet
    Else
        g_objConnection.Execute strSql, lngRecEff
    End If
    Set objg_objRecordSet = Nothing
    bolRecordset = Empty
End Function
Sub CloseDB()
    On Error Resume Next
    g_objConnection.Close
    ‘
    On Error GoTo 0
    If Not g_objConnection Is Nothing Then
        If g_objConnection.State = 1 Then g_objConnection.Close
    End If
‘    If Not g_objRecordSet Is Nothing Then
‘        If g_objRecordSet.State = 1 Then
‘    End If
    Set g_objConnection = Nothing
    ‘Set g_objRecordSet = Nothing
End Sub
Function ChangeColumnName(ByVal strDBFullPath As String, ByVal strTabName As String, _
                     ByVal strOldColName As String, ByVal strNewColName As String) As Boolean
    Dim objCat                  As Object
    Dim objTbl                  As Object
    Const strMsgBoxTitle        As String = “Change Column Name”
On Error GoTo XitPoint
    Set objCat = CreateObject(“ADOX.Catalog”)
    Set objTbl = CreateObject(“ADOX.Table”)
    objCat.ActiveConnection = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source= ” & strDBFullPath
    Set objTbl = objCat.Tables(strTabName)
    objTbl.Columns(strOldColName).Name = strNewColName
    objCat.ActiveConnection.Close
    ChangeColumnName = True
    Exit Function
XitPoint:
    If Err.Number = 3265 Then
        MsgBox “Given table\column is not found. Please check if the given table\column exist.”, vbCritical, strMsgBoxTitle
    ElseIf Err.Number <> 3265 And Err.Number <> 0 Then
        MsgBox “Error Number:- ” & Err.Number & vbLf & “Error Description:- ” & Err.Description, vbCritical, strMsgBoxTitle
    End If
    Err.Clear
    On Error GoTo 0
    ChangeColumnName = False
End Function
Sub ModifyQryDef(ByVal strQryName As String, ByVal strNewQryDef As String, _
                 ByVal strRplwhat As String, ByVal strRplwith As String, _
                 ByVal QrySchemaType As QrySchema, Optional blnReplace As Boolean = False)
    Dim objCmd                  As Object
    Dim objCat                  As Object
    Dim objCmdType              As Object
On Error GoTo XitPoint
    ‘Checking for db connection
    Call blnConnectDB
    ‘Creating ADOX Object
    Set objCat = CreateObject(“ADOX.Catalog”)
    Set objCat.ActiveConnection = g_objConnection
    ‘Checking query type
    Select Case QrySchemaType
        Case 16 ‘Procedures
            Set objCmdType = objCat.Procedures(strQryName)
        Case 20 ‘Tables
            Set objCmdType = objCat.Tables(strQryName)
        Case 23 ‘Views
            Set objCmdType = objCat.Views(strQryName)
    End Select
    ‘Getting commond object
    Set objCmd = objCmdType.Command
    ‘If need to replace query
    If blnReplace Then
        strNewQryDef = objCmd.CommandText
        strNewQryDef = Replace(strNewQryDef, strRplwhat, strRplwith)
    End If
    ‘Modifying query
    objCmd.CommandText = strNewQryDef
    Set objCmdType.Command = objCmd
XitPoint:
    If Err.Number <> 0 Then
        MsgBox “Err. Number:- ” & Err.Number & vbLf & vbLf & “Err. Description:- ” & Err.Description, vbCritical, “Database”
        Err.Clear
        On Error GoTo 0
    End If
    Set objCmdType = Nothing
    Set objCmd = Nothing
    Set objCat = Nothing
End Sub
Sub CreateProcedure(ByVal strProName As String, ByVal strQry As String, Optional blnShowErrMsg As Boolean = False)
    Dim objCmd                  As Object
    Dim objCat                  As Object
On Error GoTo XitPoint
    ‘Checking for db connection
    Call blnConnectDB
    ‘Creating ADOX Object
    Set objCat = CreateObject(“ADOX.Catalog”)
    Set objCat.ActiveConnection = g_objConnection
    ‘Getting commond object
    Set objCmd = CreateObject(“ADODB.Command”)
    ‘Modifying query
    objCmd.CommandText = strQry
    objCat.Views.Append strProName, objCmd
XitPoint:
    If Err.Number <> 0 Then
        If blnShowErrMsg Then
            MsgBox “Err. Number:- ” & Err.Number & vbLf & vbLf & “Err. Description:- ” & Err.Description, vbCritical, “Database”
        End If
        Err.Clear
        On Error GoTo 0
    End If
    Set objCmd = Nothing
    Set objCat = Nothing
End Sub