Difference between revisions of "Microsoft Access VBA Code Snippets"

From database24
Jump to navigation Jump to search
Line 3: Line 3:
  
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Dim cn As ADODB.Connection
+
    Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
+
    Dim rs As ADODB.Recordset
+
   
Set cn = CurrentProject.Connection
+
    Set cn = CurrentProject.Connection
Set rs = New ADODB.Recordset
+
    Set rs = New ADODB.Recordset
With rs
+
    With rs
    .Open _
+
        .Open _
        Source:="SELECT * FROM tblTable", _
+
            Source:="SELECT * FROM tblTable", _
        ActiveConnection:=cn
+
            ActiveConnection:=cn
    .MoveFirst
+
        .MoveFirst
    Do While Not .EOF
+
        Do While Not .EOF
        'Record based instructions
+
            'Record based instructions
        .MoveNext
+
            .MoveNext
    Loop
+
        Loop
    .Close
+
        .Close
End With
+
    End With
+
   
Set rs = Nothing
+
    Set rs = Nothing
Set cn = Nothing
+
    Set cn = Nothing
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Line 30: Line 30:
 
=== getApplicationTitle ===
 
=== getApplicationTitle ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Function getApplicationTitle() As String
+
    Function getApplicationTitle() As String
    Dim strResult As String
+
        Dim strResult As String
   
+
       
    strResult = CurrentDb.Properties("AppTitle").Value
+
        strResult = CurrentDb.Properties("AppTitle").Value
   
+
       
    getApplicationTitle = strResult
+
        getApplicationTitle = strResult
End Function
+
    End Function
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Line 43: Line 43:
  
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Function getProjectName() As String
+
    Function getProjectName() As String
    Dim strResult As String
+
        Dim strResult As String
   
+
       
    strResult = Application.VBE.ActiveVBProject.Name
+
        strResult = Application.VBE.ActiveVBProject.Name
   
+
       
    getDbAppTitle = strResult
+
        getDbAppTitle = strResult
End Function
+
    End Function
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
=== setDebug ===
 
=== setDebug ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Sub setDebug(blnDebug As Boolean)
+
    Sub setDebug(blnDebug As Boolean)
    saveSetting getProjectName, "RunTime", "Debug", CStr(blnDebug)
+
        saveSetting getProjectName, "RunTime", "Debug", CStr(blnDebug)
End Sub
+
    End Sub
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
=== isDebug ===
 
=== isDebug ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Function isDebug() As Boolean
+
    Function isDebug() As Boolean
    Dim blnResult As Boolean
+
        Dim blnResult As Boolean
   
+
       
    blnResult = CBool(GetSetting(getProjectName, "RunTime", "Debug", 0))
+
        blnResult = CBool(GetSetting(getProjectName, "RunTime", "Debug", 0))
   
+
       
    isDebug = blnResult
+
        isDebug = blnResult
End Function
+
    End Function
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
=== existsTable ===
 
=== existsTable ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Function existsTable(strTable As String) As Boolean
+
    Function existsTable(strTable As String) As Boolean
    Dim blnResult As Boolean
+
        Dim blnResult As Boolean
    Dim tdf As TableDef
+
        Dim tdf As TableDef
   
+
       
    blnResult = False
+
        blnResult = False
    For Each tdf In CurrentDb.TableDefs
+
        For Each tdf In CurrentDb.TableDefs
        If tdf.Name = strTable Then
+
            If tdf.Name = strTable Then
            blnResult = True
+
                blnResult = True
            Exit For
+
                Exit For
        End If
+
            End If
    Next
+
        Next
   
+
       
    existsTable = blnResult
+
        existsTable = blnResult
End Function
+
    End Function
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
=== existsQuery ===
 
=== existsQuery ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Function existsQuery(strQuery As String) As Boolean
+
    Function existsQuery(strQuery As String) As Boolean
    Dim blnResult As Boolean
+
        Dim blnResult As Boolean
    Dim qdf As QueryDef
+
        Dim qdf As QueryDef
   
+
       
    blnResult = False
+
        blnResult = False
    For Each qdf In CurrentDb.QueryDefs
+
        For Each qdf In CurrentDb.QueryDefs
        If qdf.Name = strQuery Then
+
            If qdf.Name = strQuery Then
            blnResult = True
+
                blnResult = True
            Exit For
+
                Exit For
        End If
+
            End If
    Next
+
        Next
   
+
       
    existsQuery = blnResult
+
        existsQuery = blnResult
End Function
+
    End Function
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
=== inList ===
 
=== inList ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Public Function inList(cmb As ComboBox, var As Variant) As Boolean
+
    Public Function inList(cmb As ComboBox, var As Variant) As Boolean
    Dim blnResult As Boolean
+
        Dim blnResult As Boolean
    Dim intIndex As Integer
+
        Dim intIndex As Integer
   
+
       
    blnResult = False
+
        blnResult = False
    With cmb
+
        With cmb
        For intIndex = Abs(.ColumnHeads) To .ListCount - 1
+
            For intIndex = Abs(.ColumnHeads) To .ListCount - 1
            If CLng(.ItemData(intIndex)) = CLng(Nz(var)) Then
+
                If CLng(.ItemData(intIndex)) = CLng(Nz(var)) Then
                blnResult = True
+
                    blnResult = True
                Exit For
+
                    Exit For
            End If
+
                End If
        Next
+
            Next
    End With
+
        End With
   
+
       
    inList = blnResult
+
        inList = blnResult
End Function
+
    End Function
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Line 130: Line 130:
  
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Sub displayActiveUsers()
+
    Sub displayActiveUsers()
    Dim strUsers As String
+
        Dim strUsers As String
    Dim cn As New ADODB.Connection
+
        Dim cn As New ADODB.Connection
    Dim rs As New ADODB.Recordset
+
        Dim rs As New ADODB.Recordset
    Dim wshNet As WshNetwork
+
        Dim wshNet As WshNetwork
+
   
    strUsers = "Computer Name"
+
        strUsers = "Computer Name"
    Set cn = CurrentProject.Connection
+
        Set cn = CurrentProject.Connection
    Set rs = cn.OpenSchema( _
+
        Set rs = cn.OpenSchema( _
        Schema:=adSchemaProviderSpecific, _
+
            Schema:=adSchemaProviderSpecific, _
        SchemaId:="{947bb102-5d43-11d1-bdbf-00c04fb92675}" _
+
            SchemaId:="{947bb102-5d43-11d1-bdbf-00c04fb92675}" _
        )
+
            )
    Debug.Print _
+
        Debug.Print _
        rs.Fields(0).Name & " " & _
+
            rs.Fields(0).Name & " " & _
        rs.Fields(1).Name ' & " " & _
+
            rs.Fields(1).Name ' & " " & _
        rs.Fields(2).Name & " " & _
+
            rs.Fields(2).Name & " " & _
        rs.Fields(3).Name
+
            rs.Fields(3).Name
    Set wshNet = New WshNetwork
+
        Set wshNet = New WshNetwork
    With rs
+
        With rs
        Do While Not .EOF
+
            Do While Not .EOF
            strUsers = strUsers & vbCrLf & Chr$(149) & "  " & Left(.Fields(0).Value, Len(wshNet.ComputerName))
+
                strUsers = strUsers & vbCrLf & Chr$(149) & "  " & Left(.Fields(0).Value, Len(wshNet.ComputerName))
            If Left(.Fields(0).Value, Len(wshNet.ComputerName)) = wshNet.ComputerName Then
+
                If Left(.Fields(0).Value, Len(wshNet.ComputerName)) = wshNet.ComputerName Then
                strUsers = strUsers & " (me)"
+
                    strUsers = strUsers & " (me)"
                Debug.Print _
+
                    Debug.Print _
                    wshNet.ComputerName & "*    " & _
+
                        wshNet.ComputerName & "*    " & _
                    wshNet.UserName ' & " " & _
+
                        wshNet.UserName ' & " " & _
                    .Fields(2).Value & " " & _
+
                        .Fields(2).Value & " " & _
                    .Fields(3).Value
+
                        .Fields(3).Value
            Else
+
                Else
                Debug.Print _
+
                    Debug.Print _
                    Left(.Fields(0).Value, Len(wshNet.ComputerName)) & "      " & _
+
                        Left(.Fields(0).Value, Len(wshNet.ComputerName)) & "      " & _
                    Trim(.Fields(1).Value) ' & " " & _
+
                        Trim(.Fields(1).Value) ' & " " & _
                    .Fields(2).Value & " " & _
+
                        .Fields(2).Value & " " & _
                    .Fields(3).Value
+
                        .Fields(3).Value
            End If
+
                End If
            .MoveNext
+
                .MoveNext
        Loop
+
            Loop
    End With
+
        End With
    MsgBox strUsers, vbOKOnly, "Current Users"
+
        MsgBox strUsers, vbOKOnly, "Current Users"
End Sub
+
    End Sub
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Line 177: Line 177:
 
=== debugPrintUserRunTimeSettings ===
 
=== debugPrintUserRunTimeSettings ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Sub debugPrintUserRunTimeSettings()
+
    Sub debugPrintUserRunTimeSettings()
    Dim arrSetting() As String
+
        Dim arrSetting() As String
    Dim intIndex As Integer
+
        Dim intIndex As Integer
   
+
       
    Debug.Print
+
        Debug.Print
    Debug.Print "User RunTime Settings"
+
        Debug.Print "User RunTime Settings"
    Debug.Print "---------------------"
+
        Debug.Print "---------------------"
    On Error GoTo handleGetAllSettingsError
+
        On Error GoTo handleGetAllSettingsError
    arrSetting = GetAllSettings(getProjectName, "RunTime")
+
        arrSetting = GetAllSettings(getProjectName, "RunTime")
    On Error GoTo 0
+
        On Error GoTo 0
    For intIndex = LBound(arrSetting) To UBound(arrSetting)
+
        For intIndex = LBound(arrSetting) To UBound(arrSetting)
        Debug.Print arrSetting(intIndex, 0) & " : " & arrSetting(intIndex, 1)
+
            Debug.Print arrSetting(intIndex, 0) & " : " & arrSetting(intIndex, 1)
    Next
+
        Next
    Exit Sub
+
        Exit Sub
   
+
       
handleGetAllSettingsError:
+
    handleGetAllSettingsError:
    Debug.Print "No user settings available."
+
        Debug.Print "No user settings available."
End Sub
+
    End Sub
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
=== deleteUserSettings ===
 
=== deleteUserSettings ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Sub deleteUserSettings()
+
    Sub deleteUserSettings()
    Debug.Print
+
        Debug.Print
    Debug.Print "User Settings"
+
        Debug.Print "User Settings"
    Debug.Print "-------------"
+
        Debug.Print "-------------"
    On Error Resume Next
+
        On Error Resume Next
    DeleteSetting getProjectName
+
        DeleteSetting getProjectName
    Debug.Print "All user settings deleted."
+
        Debug.Print "All user settings deleted."
End Sub
+
    End Sub
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Line 214: Line 214:
 
=== setStatus ===
 
=== setStatus ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Public Sub setStatus(Optional strMessage As String = "Bereit")
+
    Public Sub setStatus(Optional strMessage As String = "Bereit")
    strMessage = _
+
        strMessage = _
        getUserName & " - " & _
+
            getUserName & " - " & _
        strMessage
+
            strMessage
    SysCmd acSysCmdSetStatus, strMessage
+
        SysCmd acSysCmdSetStatus, strMessage
End Sub
+
    End Sub
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Line 229: Line 229:
  
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Public Function Round2(dblValue As Double, intDecimal As Integer) As Double
+
    Public Function Round2(dblValue As Double, intDecimal As Integer) As Double
    Dim dblResult As Double
+
        Dim dblResult As Double
   
+
       
    dblResult = CLng(dblValue * 10 ^ intDecimal) / 10 ^ intDecimal
+
        dblResult = CLng(dblValue * 10 ^ intDecimal) / 10 ^ intDecimal
   
+
       
    Round2 = dblResult
+
        Round2 = dblResult
End Function
+
    End Function
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Line 242: Line 242:
 
=== Constants ===
 
=== Constants ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Public Const strFormatSqlDate As String = "yyyy\-mm\-dd"
+
    Public Const strFormatSqlDate As String = "yyyy\-mm\-dd"
Public Const strFormatSqlDateCriterion As String = "\#yyyy\-mm\-dd\#"
+
    Public Const strFormatSqlDateCriterion As String = "\#yyyy\-mm\-dd\#"
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
=== executeSql ===
 
=== executeSql ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Public Function executeSql(strSql As String) As Long
+
    Public Function executeSql(strSql As String) As Long
    Dim lngResult As Long
+
        Dim lngResult As Long
   
+
       
    Const strFormatHms As String = "hh:mm:ss"
+
        Const strFormatHms As String = "hh:mm:ss"
   
+
       
    Dim datStart As Date
+
        Dim datStart As Date
   
+
       
    lngResult = 0
+
        lngResult = 0
   
+
       
    If isDebug Then
+
        If isDebug Then
        Debug.Print "----------------------------------------"
+
            Debug.Print "----------------------------------------"
        Debug.Print strSql
+
            Debug.Print strSql
        Debug.Print
+
            Debug.Print
        datStart = Now
+
            datStart = Now
        Debug.Print "Start      : " & Format(datStart, strFormatHms)
+
            Debug.Print "Start      : " & Format(datStart, strFormatHms)
    End If
+
        End If
+
   
    With CurrentDb
+
        With CurrentDb
        'DoCmd.SetWarnings False
+
            'DoCmd.SetWarnings False
        'On Error GoTo handleExecuteSqlError
+
            'On Error GoTo handleExecuteSqlError
        If isDebug Then
+
            If isDebug Then
            .Execute strSql, dbFailOnError
+
                .Execute strSql, dbFailOnError
        Else
+
            Else
            .Execute strSql
+
                .Execute strSql
        End If
+
            End If
        'On Error GoTo 0
+
            'On Error GoTo 0
        'DoCmd.SetWarnings True
+
            'DoCmd.SetWarnings True
        DoEvents
+
            DoEvents
       
+
           
        Select Case .RecordsAffected
+
            Select Case .RecordsAffected
        Case 1
+
            Case 1
            'Last inserted id
+
                'Last inserted id
            lngResult = .OpenRecordset("SELECT @@IDENTITY")(0)
+
                lngResult = .OpenRecordset("SELECT @@IDENTITY")(0)
        Case Else
+
            Case Else
            'Number of affected records
+
                'Number of affected records
            lngResult = .RecordsAffected
+
                lngResult = .RecordsAffected
        End Select
+
            End Select
    End With
+
        End With
   
+
       
    If isDebug Then
+
        If isDebug Then
        Debug.Print "End        : " & Format(Now, strFormatHms)
+
            Debug.Print "End        : " & Format(Now, strFormatHms)
        Debug.Print "            " & "--------"
+
            Debug.Print "            " & "--------"
        Debug.Print "Duration  : " & Format(Now - datStart, strFormatHms)
+
            Debug.Print "Duration  : " & Format(Now - datStart, strFormatHms)
        Debug.Print "Records    : " & Format(lngResult, "#,##0")
+
            Debug.Print "Records    : " & Format(lngResult, "#,##0")
        Debug.Print "----------------------------------------"
+
            Debug.Print "----------------------------------------"
        Debug.Print
+
            Debug.Print
    End If
+
        End If
+
   
    executeSql = lngResult
+
        executeSql = lngResult
    'Exit Function
+
        'Exit Function
   
+
       
'handleExecuteSqlError:
+
    'handleExecuteSqlError:
'    On Error GoTo handleExecuteSqlErrorFinal
+
    '    On Error GoTo handleExecuteSqlErrorFinal
'    DoCmd.RunSQL strSql
+
    '    DoCmd.RunSQL strSql
'    On Error GoTo 0
+
    '    On Error GoTo 0
End Function
+
    End Function
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
=== showSqlResult ===
 
=== showSqlResult ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Public Sub showSqlResult(strSql As String, Optional strQuery As String = "")
+
    Public Sub showSqlResult(strSql As String, Optional strQuery As String = "")
    Dim dbs As Database
+
        Dim dbs As Database
    Dim qdf As QueryDef
+
        Dim qdf As QueryDef
   
+
       
    If strQuery = "" Then
+
        If strQuery = "" Then
        strQuery = "SQL Result"
+
            strQuery = "SQL Result"
    End If
+
        End If
    If existsQuery(strQuery) Then
+
        If existsQuery(strQuery) Then
        DoCmd.DeleteObject acQuery, strQuery
+
            DoCmd.DeleteObject acQuery, strQuery
    End If
+
        End If
    Set dbs = CurrentDb
+
        Set dbs = CurrentDb
    Set qdf = dbs.CreateQueryDef(Name:=strQuery, SQLText:=strSql)
+
        Set qdf = dbs.CreateQueryDef(Name:=strQuery, SQLText:=strSql)
    DoCmd.OpenQuery strQuery
+
        DoCmd.OpenQuery strQuery
    Do While CurrentData.AllQueries(strQuery).IsLoaded
+
        Do While CurrentData.AllQueries(strQuery).IsLoaded
        DoEvents
+
            DoEvents
    Loop
+
        Loop
    DoCmd.DeleteObject acQuery, strQuery
+
        DoCmd.DeleteObject acQuery, strQuery
    Set qdf = Nothing
+
        Set qdf = Nothing
End Sub
+
    End Sub
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
=== getSqlAmount ===
 
=== getSqlAmount ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Public Function getSqlAmount(cur As Currency) As String
+
    Public Function getSqlAmount(cur As Currency) As String
    Dim strResult As String
+
        Dim strResult As String
   
+
       
    strResult = CStr(cur)
+
        strResult = CStr(cur)
    strResult = Replace( _
+
        strResult = Replace( _
        Expression:=strResult, _
+
            Expression:=strResult, _
        Find:=",", _
+
            Find:=",", _
        Replace:=".", _
+
            Replace:=".", _
        Compare:=vbTextCompare _
+
            Compare:=vbTextCompare _
        )
+
            )
   
+
       
    getSqlAmount = strResult
+
        getSqlAmount = strResult
End Function
+
    End Function
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
=== getSqlDate ===
 
=== getSqlDate ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Public Function getSqlDate(dat As Date) As String
+
    Public Function getSqlDate(dat As Date) As String
    Dim strResult As String
+
        Dim strResult As String
   
+
       
    strResult = Format(dat, strFormatSqlDate)
+
        strResult = Format(dat, strFormatSqlDate)
   
+
       
    getSqlDate = strResult
+
        getSqlDate = strResult
End Function
+
    End Function
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
=== getSqlDateCriterion ===
 
=== getSqlDateCriterion ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Public Function getSqlDateCriterion(dat As Date) As String
+
    Public Function getSqlDateCriterion(dat As Date) As String
    Dim strResult As String
+
        Dim strResult As String
   
+
       
    strResult = Format(dat, strFormatSqlDateCriterion)
+
        strResult = Format(dat, strFormatSqlDateCriterion)
   
+
       
    getSqlDateCriterion = strResult
+
        getSqlDateCriterion = strResult
End Function
+
    End Function
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Line 373: Line 373:
 
=== assurePath ===
 
=== assurePath ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Sub assurePath(strPath)
+
    Sub assurePath(strPath)
    Dim fso As FileSystemObject
+
        Dim fso As FileSystemObject
    Dim blnFirst As Boolean
+
        Dim blnFirst As Boolean
   
+
       
    blnFirst = True
+
        blnFirst = True
    Set fso = New FileSystemObject
+
        Set fso = New FileSystemObject
    With fso
+
        With fso
        If Not .FolderExists(strPath) Then
+
            If Not .FolderExists(strPath) Then
            On Error GoTo handleCreateFolderError
+
                On Error GoTo handleCreateFolderError
            .CreateFolder strPath
+
                .CreateFolder strPath
            On Error GoTo 0
+
                On Error GoTo 0
        End If
+
            End If
    End With
+
        End With
    Set fso = Nothing
+
        Set fso = Nothing
    Exit Sub
+
        Exit Sub
   
+
       
handleCreateFolderError:
+
    handleCreateFolderError:
    If Err.Number = 76 And blnFirst Then
+
        If Err.Number = 76 And blnFirst Then
        Debug.Print strPath & " not found - trying to create parent ..."
+
            Debug.Print strPath & " not found - trying to create parent ..."
        assurePath fso.GetParentFolderName(strPath)
+
            assurePath fso.GetParentFolderName(strPath)
        blnFirst = False
+
            blnFirst = False
        Resume
+
            Resume
    Else
+
        Else
        MsgBox "The path '" & strPath & "' could not be found, nor created.", vbExclamation + vbOKOnly
+
            MsgBox "The path '" & strPath & "' could not be found, nor created.", vbExclamation + vbOKOnly
    End If
+
        End If
End Sub
+
    End Sub
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Line 407: Line 407:
 
=== getUserName ===
 
=== getUserName ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Function getUserName() As String
+
    Function getUserName() As String
    Dim strResult As String
+
        Dim strResult As String
   
+
       
    Dim wshNet As WshNetwork
+
        Dim wshNet As WshNetwork
   
+
       
    Set wshNet = New WshNetwork
+
        Set wshNet = New WshNetwork
    strResult = wshNet.UserName
+
        strResult = wshNet.UserName
   
+
       
    getUserName = strResult
+
        getUserName = strResult
End Function
+
    End Function
 
</syntaxhighlight>
 
</syntaxhighlight>
 
   
 
   
 
=== getComputerName ===
 
=== getComputerName ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Function getComputerName() As String
+
    Function getComputerName() As String
    Dim strResult As String
+
        Dim strResult As String
   
+
       
    Dim wshNet As WshNetwork
+
        Dim wshNet As WshNetwork
   
+
       
    Set wshNet = New WshNetwork
+
        Set wshNet = New WshNetwork
    strResult = wshNet.ComputerName
+
        strResult = wshNet.ComputerName
   
+
       
    getComputerName = strResult
+
        getComputerName = strResult
End Function
+
    End Function
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Line 437: Line 437:
 
=== Variables ===
 
=== Variables ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Private xl As Excel.Application
+
    Private xl As Excel.Application
Private blnCreated As Boolean
+
    Private blnCreated As Boolean
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
=== getExcel ===
 
=== getExcel ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Private Function getExcel() As Excel.Application
+
    Private Function getExcel() As Excel.Application
    If xl Is Nothing Then
+
        If xl Is Nothing Then
        On Error Resume Next
+
            On Error Resume Next
        Set xl = GetObject(, "Excel.Application")
+
            Set xl = GetObject(, "Excel.Application")
        On Error GoTo 0
+
            On Error GoTo 0
        If xl Is Nothing Then
+
            If xl Is Nothing Then
            Set xl = CreateObject("Excel.Application")
+
                Set xl = CreateObject("Excel.Application")
            xl.Visible = True
+
                xl.Visible = True
            blnCreated = True
+
                blnCreated = True
        Else
+
            Else
            blnCreated = False
+
                blnCreated = False
        End If
+
            End If
    End If
+
        End If
   
+
       
    Set getExcel = xl
+
        Set getExcel = xl
End Function
+
    End Function
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
=== quitExcel ===
 
=== quitExcel ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Sub quitExcel()
+
    Sub quitExcel()
    With xl
+
        With xl
        If blnCreated Then
+
            If blnCreated Then
            .Quit
+
                .Quit
        End If
+
            End If
        Set xl = Nothing
+
            Set xl = Nothing
    End With
+
        End With
End Sub
+
    End Sub
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
=== openExcelWorkbook ===
 
=== openExcelWorkbook ===
 
<syntaxhighlight lang="vb">
 
<syntaxhighlight lang="vb">
Public Function openExcelWorkbook(strPathFile As String) As Excel.Workbook
+
    Public Function openExcelWorkbook(strPathFile As String) As Excel.Workbook
    Dim wbkResult As Excel.Workbook
+
        Dim wbkResult As Excel.Workbook
   
+
       
    With getExcel
+
        With getExcel
        Set wbkResult = .Workbooks.Open(strPathFile)
+
            Set wbkResult = .Workbooks.Open(strPathFile)
    End With
+
        End With
   
+
       
    Set openExcelWorkbook = wbkResult
+
        Set openExcelWorkbook = wbkResult
End Function
+
    End Function
 
</syntaxhighlight>
 
</syntaxhighlight>
  
 
=== closeExcelWorkbook ===
 
=== closeExcelWorkbook ===
 
</syntaxhighlight lang="vb">
 
</syntaxhighlight lang="vb">
Public Sub closeExcelWorkbook(strWorkbook As String, Optional blnQuit As Boolean = False)
+
    Public Sub closeExcelWorkbook(strWorkbook As String, Optional blnQuit As Boolean = False)
    With xl
+
        With xl
        .Workbooks(strWorkbook).Close
+
            .Workbooks(strWorkbook).Close
        If blnQuit Then
+
            If blnQuit Then
            quitExcel
+
                quitExcel
        End If
+
            End If
    End With
+
        End With
End Sub
+
    End Sub
 
</syntaxhighlight>
 
</syntaxhighlight>

Revision as of 06:27, 30 January 2010

ActiveX Data Objects

Retrieving and processing a recordset works like this

    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    
    Set cn = CurrentProject.Connection
    Set rs = New ADODB.Recordset
    With rs
        .Open _
            Source:="SELECT * FROM tblTable", _
            ActiveConnection:=cn
        .MoveFirst
        Do While Not .EOF
            'Record based instructions
            .MoveNext
        Loop
        .Close
    End With
    
    Set rs = Nothing
    Set cn = Nothing


modAccess

modAccess consists basically of methods, which are specific to Microsoft Access like methods for retrieving information about properties, checking Access objects for their existence.

getApplicationTitle

    Function getApplicationTitle() As String
        Dim strResult As String
        
        strResult = CurrentDb.Properties("AppTitle").Value
        
        getApplicationTitle = strResult
    End Function

getProjectName

The first guess for this is usually CurrentProject.Name but unfortunately this just returns the name of the file. If you want to bind your settings to a certain project, you certainly don't want to rely on the exact naming of a file; to the contrary you want to be able to use your stored settings no matter what the database file is named.

    Function getProjectName() As String
        Dim strResult As String
        
        strResult = Application.VBE.ActiveVBProject.Name
        
        getDbAppTitle = strResult
    End Function

setDebug

    Sub setDebug(blnDebug As Boolean)
        saveSetting getProjectName, "RunTime", "Debug", CStr(blnDebug)
    End Sub

isDebug

    Function isDebug() As Boolean
        Dim blnResult As Boolean
        
        blnResult = CBool(GetSetting(getProjectName, "RunTime", "Debug", 0))
        
        isDebug = blnResult
    End Function

existsTable

    Function existsTable(strTable As String) As Boolean
        Dim blnResult As Boolean
        Dim tdf As TableDef
        
        blnResult = False
        For Each tdf In CurrentDb.TableDefs
            If tdf.Name = strTable Then
                blnResult = True
                Exit For
            End If
        Next
        
        existsTable = blnResult
    End Function

existsQuery

    Function existsQuery(strQuery As String) As Boolean
        Dim blnResult As Boolean
        Dim qdf As QueryDef
        
        blnResult = False
        For Each qdf In CurrentDb.QueryDefs
            If qdf.Name = strQuery Then
                blnResult = True
                Exit For
            End If
        Next
        
        existsQuery = blnResult
    End Function

inList

    Public Function inList(cmb As ComboBox, var As Variant) As Boolean
        Dim blnResult As Boolean
        Dim intIndex As Integer
        
        blnResult = False
        With cmb
            For intIndex = Abs(.ColumnHeads) To .ListCount - 1
                If CLng(.ItemData(intIndex)) = CLng(Nz(var)) Then
                    blnResult = True
                    Exit For
                End If
            Next
        End With
        
        inList = blnResult
    End Function

displayActiveUsers

The usage of the Windows Script Host Object in order to identify the user's workstation is optional.

    Sub displayActiveUsers()
        Dim strUsers As String
        Dim cn As New ADODB.Connection
        Dim rs As New ADODB.Recordset
        Dim wshNet As WshNetwork
    
        strUsers = "Computer Name"
        Set cn = CurrentProject.Connection
        Set rs = cn.OpenSchema( _
            Schema:=adSchemaProviderSpecific, _
            SchemaId:="{947bb102-5d43-11d1-bdbf-00c04fb92675}" _
            )
        Debug.Print _
            rs.Fields(0).Name & " " & _
            rs.Fields(1).Name ' & " " & _
            rs.Fields(2).Name & " " & _
            rs.Fields(3).Name
        Set wshNet = New WshNetwork
        With rs
            Do While Not .EOF
                strUsers = strUsers & vbCrLf & Chr$(149) & "  " & Left(.Fields(0).Value, Len(wshNet.ComputerName))
                If Left(.Fields(0).Value, Len(wshNet.ComputerName)) = wshNet.ComputerName Then
                    strUsers = strUsers & " (me)"
                    Debug.Print _
                        wshNet.ComputerName & "*     " & _
                        wshNet.UserName ' & " " & _
                        .Fields(2).Value & " " & _
                        .Fields(3).Value
                Else
                    Debug.Print _
                        Left(.Fields(0).Value, Len(wshNet.ComputerName)) & "      " & _
                        Trim(.Fields(1).Value) ' & " " & _
                        .Fields(2).Value & " " & _
                        .Fields(3).Value
                End If
                .MoveNext
            Loop
        End With
        MsgBox strUsers, vbOKOnly, "Current Users"
    End Sub


modSetting

debugPrintUserRunTimeSettings

    Sub debugPrintUserRunTimeSettings()
        Dim arrSetting() As String
        Dim intIndex As Integer
        
        Debug.Print
        Debug.Print "User RunTime Settings"
        Debug.Print "---------------------"
        On Error GoTo handleGetAllSettingsError
        arrSetting = GetAllSettings(getProjectName, "RunTime")
        On Error GoTo 0
        For intIndex = LBound(arrSetting) To UBound(arrSetting)
            Debug.Print arrSetting(intIndex, 0) & " : " & arrSetting(intIndex, 1)
        Next
        Exit Sub
        
    handleGetAllSettingsError:
        Debug.Print "No user settings available."
    End Sub

deleteUserSettings

    Sub deleteUserSettings()
        Debug.Print
        Debug.Print "User Settings"
        Debug.Print "-------------"
        On Error Resume Next
        DeleteSetting getProjectName
        Debug.Print "All user settings deleted."
    End Sub


modUi

setStatus

    Public Sub setStatus(Optional strMessage As String = "Bereit")
        strMessage = _
            getUserName & " - " & _
            strMessage
        SysCmd acSysCmdSetStatus, strMessage
    End Sub


modFunction

Round2

Microsoft Access' Round() function is different from the one implemented in Microsoft Excel. The behavious can be imitated using a user defined function.

    Public Function Round2(dblValue As Double, intDecimal As Integer) As Double
        Dim dblResult As Double
        
        dblResult = CLng(dblValue * 10 ^ intDecimal) / 10 ^ intDecimal
        
        Round2 = dblResult
    End Function

modSql

Constants

    Public Const strFormatSqlDate As String = "yyyy\-mm\-dd"
    Public Const strFormatSqlDateCriterion As String = "\#yyyy\-mm\-dd\#"

executeSql

    Public Function executeSql(strSql As String) As Long
        Dim lngResult As Long
        
        Const strFormatHms As String = "hh:mm:ss"
        
        Dim datStart As Date
        
        lngResult = 0
        
        If isDebug Then
            Debug.Print "----------------------------------------"
            Debug.Print strSql
            Debug.Print
            datStart = Now
            Debug.Print "Start      : " & Format(datStart, strFormatHms)
        End If
    
        With CurrentDb
            'DoCmd.SetWarnings False
            'On Error GoTo handleExecuteSqlError
            If isDebug Then
                .Execute strSql, dbFailOnError
            Else
                .Execute strSql
            End If
            'On Error GoTo 0
            'DoCmd.SetWarnings True
            DoEvents
            
            Select Case .RecordsAffected
            Case 1
                'Last inserted id
                lngResult = .OpenRecordset("SELECT @@IDENTITY")(0)
            Case Else
                'Number of affected records
                lngResult = .RecordsAffected
            End Select
        End With
        
        If isDebug Then
            Debug.Print "End        : " & Format(Now, strFormatHms)
            Debug.Print "             " & "--------"
            Debug.Print "Duration   : " & Format(Now - datStart, strFormatHms)
            Debug.Print "Records    : " & Format(lngResult, "#,##0")
            Debug.Print "----------------------------------------"
            Debug.Print
        End If
    
        executeSql = lngResult
        'Exit Function
        
    'handleExecuteSqlError:
    '    On Error GoTo handleExecuteSqlErrorFinal
    '    DoCmd.RunSQL strSql
    '    On Error GoTo 0
    End Function

showSqlResult

    Public Sub showSqlResult(strSql As String, Optional strQuery As String = "")
        Dim dbs As Database
        Dim qdf As QueryDef
        
        If strQuery = "" Then
            strQuery = "SQL Result"
        End If
        If existsQuery(strQuery) Then
            DoCmd.DeleteObject acQuery, strQuery
        End If
        Set dbs = CurrentDb
        Set qdf = dbs.CreateQueryDef(Name:=strQuery, SQLText:=strSql)
        DoCmd.OpenQuery strQuery
        Do While CurrentData.AllQueries(strQuery).IsLoaded
            DoEvents
        Loop
        DoCmd.DeleteObject acQuery, strQuery
        Set qdf = Nothing
    End Sub

getSqlAmount

    Public Function getSqlAmount(cur As Currency) As String
        Dim strResult As String
        
        strResult = CStr(cur)
        strResult = Replace( _
            Expression:=strResult, _
            Find:=",", _
            Replace:=".", _
            Compare:=vbTextCompare _
            )
        
        getSqlAmount = strResult
    End Function

getSqlDate

    Public Function getSqlDate(dat As Date) As String
        Dim strResult As String
        
        strResult = Format(dat, strFormatSqlDate)
        
        getSqlDate = strResult
    End Function

getSqlDateCriterion

    Public Function getSqlDateCriterion(dat As Date) As String
        Dim strResult As String
        
        strResult = Format(dat, strFormatSqlDateCriterion)
        
        getSqlDateCriterion = strResult
    End Function


modFso

assurePath

    Sub assurePath(strPath)
        Dim fso As FileSystemObject
        Dim blnFirst As Boolean
        
        blnFirst = True
        Set fso = New FileSystemObject
        With fso
            If Not .FolderExists(strPath) Then
                On Error GoTo handleCreateFolderError
                .CreateFolder strPath
                On Error GoTo 0
            End If
        End With
        Set fso = Nothing
        Exit Sub
        
    handleCreateFolderError:
        If Err.Number = 76 And blnFirst Then
            Debug.Print strPath & " not found - trying to create parent ..."
            assurePath fso.GetParentFolderName(strPath)
            blnFirst = False
            Resume
        Else
            MsgBox "The path '" & strPath & "' could not be found, nor created.", vbExclamation + vbOKOnly
        End If
    End Sub


modWsh

Windows Scripting Host Object based methods

getUserName

    Function getUserName() As String
        Dim strResult As String
        
        Dim wshNet As WshNetwork
        
        Set wshNet = New WshNetwork
        strResult = wshNet.UserName
        
        getUserName = strResult
    End Function

getComputerName

    Function getComputerName() As String
        Dim strResult As String
        
        Dim wshNet As WshNetwork
        
        Set wshNet = New WshNetwork
        strResult = wshNet.ComputerName
        
        getComputerName = strResult
    End Function

modExcel

Variables

    Private xl As Excel.Application
    Private blnCreated As Boolean

getExcel

    Private Function getExcel() As Excel.Application
        If xl Is Nothing Then
            On Error Resume Next
            Set xl = GetObject(, "Excel.Application")
            On Error GoTo 0
            If xl Is Nothing Then
                Set xl = CreateObject("Excel.Application")
                xl.Visible = True
                blnCreated = True
            Else
                blnCreated = False
            End If
        End If
        
        Set getExcel = xl
    End Function

quitExcel

    Sub quitExcel()
        With xl
            If blnCreated Then
                .Quit
            End If
            Set xl = Nothing
        End With
    End Sub

openExcelWorkbook

    Public Function openExcelWorkbook(strPathFile As String) As Excel.Workbook
        Dim wbkResult As Excel.Workbook
        
        With getExcel
            Set wbkResult = .Workbooks.Open(strPathFile)
        End With
        
        Set openExcelWorkbook = wbkResult
    End Function

closeExcelWorkbook

</syntaxhighlight lang="vb">

   Public Sub closeExcelWorkbook(strWorkbook As String, Optional blnQuit As Boolean = False)
       With xl
           .Workbooks(strWorkbook).Close
           If blnQuit Then
               quitExcel
           End If
       End With
   End Sub

</syntaxhighlight>