-
I attached an example xls and mdb. The xls uses both this mdb method and the hidden worksheet methods.
To use this code in your workbook, right click the Excel icon just to the left of the File menu, View Code and paste this. You will need to add the ActiveX reference as commented.
You will need to change the path to where you store the mdb if not in that workbook's path in variables, DBFullName and s. This code has more comments in the attached xls to do other things. You can delete them as I did here.
This adds a record for both Open and Close events.
[vba]Private Sub Workbook_BeforeClose(Cancel As Boolean)
UpdateMDB "Close"
End Sub
Private Sub Workbook_Open()
UpdateMDB "Open"
End Sub
Private Sub UpdateMDB(wbEvent As String)
' the Microsoft ActiveX Data Objects 2.x Library
Dim DBFullName As String
Dim Cnct As String, Src As String
Dim Connection As ADODB.Connection
Dim Recordset As ADODB.Recordset
Dim Col As Integer, Row As Integer, s As String
'On Error GoTo EndNow
'Set window and calc off to speed updates
' Database information
DBFullName = ThisWorkbook.Path & "\Audit.mdb"
'Set a table name in the MDB
s = "tblWorkbook"
' Open the connection
Set Connection = New ADODB.Connection
Cnct = "Provider=Microsoft.Jet.OLEDB.4.0; "
Cnct = Cnct & "Data Source=" & DBFullName & ";"
Connection.Open ConnectionString:=Cnct
' Create RecordSet
Set Recordset = New ADODB.Recordset
Recordset.CursorType = adOpenKeyset
Recordset.LockType = adLockOptimistic
With Recordset
' Filter
Src = "SELECT * FROM " & s
Recordset.Open Source:=Src, ActiveConnection:=Connection
'************ Add a record and field values and update MDB table ***************
.AddNew
Recordset("WorkBook") = ThisWorkbook.FullName
Recordset("UserName") = Environ("UserName")
If wbEvent = "Open" Then Recordset("OpenDate") = Now
If wbEvent = "Close" Then Recordset("CloseDate") = Now
.Update 'Push this disconnected database to update the MDB
End With
EndNow:
Set Recordset = Nothing
Connection.Close
Set Connection = Nothing
End Sub
[/vba]
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules