Search code examples
sqlvbams-accesssql-insertms-access-2007

Use VBA to INSERT a new record into an Access 2007 database


I am still trying to learn, so please be gentle. My goal is to track users who've completed viewing a standalone MS PowerPoint by having them click a button on the last slide.

When the completeButton is clicked, it captures the Windows username and date. How can I have the event also insert both the variables as a new record into an existing MS Access 2007 database (behind the scenes)?

'Click button
Private Sub completeButton_Click()
'Get Windows user
Dim empUserName As String
empUserName = Environ("UserName")
'Get Date
Dim Completed As Date
Completed = Date
'Set Path to database
Dim Path As String
Path = "C:\TestDatabase.accdb"

'Open connection to database
'Insert empUserName and Completed variables as new record
'Close connection to database
'Display message
Msgbox("Thank you for viewing the material")
'Close presentation
With Application.Presentations
For i = .Count To 1 Step -1
    .Item(i).Close
Next
End With

Solution

  • I tested this on Office 2013, hope it would work for you too. These lines open connection, insert new entries and close the connection.

    Dim Path As String
    Dim strCon As String
    Dim con As Object
    
    Path = "C:\TestDatabase.accdb"
    strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Path
    Set con = CreateObject("ADODB.connection")
    
    con.Open strCon
    con.Execute "INSERT INTO Table1 (Field1, Field2) VALUES (""" & empUserName & """, """ & Completed & """)"
    
    con.Close
    Set con = Nothing
    

    Table1 - your table name
    Field1 - name of the column where you want to put empUserName
    Field2 - name of the column where you want to put Completed