Page 1 of 2 12 LastLast
Results 1 to 15 of 17
  1. #1
    jimrosser is offline Novice
    Windows 11 Access 2019
    Join Date
    Jan 2023
    Posts
    11

    Deleting Accees Table Records from Excel VBA

    Hi,

    Can someone help me add a line in this code to delete the current table records? I'm trying to delete the table records and then add new data.



    Thanks,
    Code:
    Option Explicit
    
    Sub AddRecordsIntoAccessTable()
            
        '-----------------------------------------------------------------------------
        'The macro opens the Sample.accdb database and adds the 7 rows from the sheet
        '"Excel Data" in the "Customers" table of the database.
        'The code uses late binding, so no reference to external library is required.
        
        'Written By:    Christos Samaras
        'Date:          27/06/2020
        'E-mail:        xristos.samaras@gmail.com
        'Site:          https://myengineeringworld.net
        '-----------------------------------------------------------------------------
    
    
        'Declaring the necessary variables.
        Dim accessFile  As String
        Dim accessTable As String
        Dim sht         As Worksheet
        Dim lastRow     As Long
        Dim lastColumn  As Integer
        Dim con         As Object
        Dim rs          As Object
        Dim sql         As String
        Dim sql1        As String
        Dim i           As Long
        Dim j           As Integer
        Dim strSheetName As String
        strSheetName = ActiveSheet.Name
                
        'Disable the screen flickering.
        Application.ScreenUpdating = False
        
        'Specify the file path of the accdb file. You can also use the full path of the file like this:
        'AccessFile = "C:\Users\Christos\Desktop\Sample.accdb"
        accessFile = ThisWorkbook.Path & "\" & "Sample.accdb"
             
        'Ensure that the Access file exists.
        If FileExists(accessFile) = False Then
            MsgBox "The Access file doesn't exist!", vbCritical, "Invalid Access file path"
            Exit Sub
        End If
        MsgBox ("Variable = " & strSheetName)
        'Set the name of the table you want to add the data.
        accessTable = strSheetName
        
                    
        'Set the worksheet that contains the data.
        On Error Resume Next
        Set sht = ThisWorkbook.ActiveSheet
        'ThisWorkbook.Sheets("Excel Data")
        If Err.Number <> 0 Then
            MsgBox "The given worksheet does not exist!", vbExclamation, "Invalid Sheet Name"
            Exit Sub
        End If
        Err.Clear
        
    
    
        'Find the last row and last column in the given worksheet.
        With sht
            lastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
            lastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
        End With
        
        'Check if there are data in the worksheet.
        If lastRow < 2 Or lastColumn < 1 Then
            MsgBox "There are no data in the given worksheet!", vbCritical, "Empty Data"
            Exit Sub
        End If
            
        'Create the ADODB connection object.
        Set con = CreateObject("ADODB.connection")
        
        'Check if the object was created.
        If Err.Number <> 0 Then
            MsgBox "The connection was not created!", vbCritical, "Connection Error"
            Exit Sub
        End If
        Err.Clear
        
        'Open the connection.
        con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & accessFile
        
        sql = "SELECT * FROM " & accessTable
        
            
        'Create the ADODB recordset object.
        Set rs = CreateObject("ADODB.Recordset")
        
        'Check if the object was created.
        If Err.Number <> 0 Then
            Set rs = Nothing
            Set con = Nothing
            MsgBox "The recordset was not created!", vbCritical, "Recordset Error"
            Exit Sub
        End If
        Err.Clear
                 
        'Set the necessary recordset properties.
        rs.CursorType = 1   'adOpenKeyset on early binding
        rs.LockType = 3     'adLockOptimistic on early binding
            
        'Open the recordset.
        rs.Open sql, con
        
        'Add the records from Excel to Access by looping through the rows and columns of the given worksheet.
        'Here the headers are in the row 1 and they are identical to the Access table headers.
        'This is the reason why, for example, there are no spaces in the headers of the sample worksheet.
        For i = 2 To lastRow
            rs.AddNew
            For j = 1 To lastColumn
                'This is how it will look like the first time (i = 2, j = 1):
                'rs("FirstName") = "Bob"
                rs(sht.Cells(1, j).Value) = sht.Cells(i, j).Value
            Next j
            rs.Update
        Next i
            
        'Close the recordet and the connection.
        rs.Close
        con.Close
        
        'Release the objects.
        Set rs = Nothing
        Set con = Nothing
        
        'Re-enable the screen.
        Application.ScreenUpdating = True
    
    
        'Inform the user that the macro was executed successfully.
        MsgBox lastRow - 1 & " rows were successfully added into the '" & accessTable & "' table!", vbInformation, "Done"
        
    End Sub

  2. #2
    Gicu's Avatar
    Gicu is offline VIP
    Windows 10 Access 2010 32bit
    Join Date
    Jul 2015
    Location
    Kelowna, BC, Canada
    Posts
    4,114
    Once you open the connection add a line to delete the records:
    Code:
    Con.Execute "DELETE * FROM [" & accesstable & "]" 'added the square brackets in case the table name contains a space or other special character
    https://www.mrexcel.com/board/thread...-excel.260124/

    Cheers,
    Vlad Cucinschi
    MS Access Developer
    http://forestbyte.com/

  3. #3
    jimrosser is offline Novice
    Windows 11 Access 2019
    Join Date
    Jan 2023
    Posts
    11
    Gicu - Thanks for the help - it's ignoring that line of code.
    con.Execute "DELETE * FROM " & accessTable

  4. #4
    Gicu's Avatar
    Gicu is offline VIP
    Windows 10 Access 2010 32bit
    Join Date
    Jul 2015
    Location
    Kelowna, BC, Canada
    Posts
    4,114
    Can you show your code again?
    Cheers,
    Vlad Cucinschi
    MS Access Developer
    http://forestbyte.com/

  5. #5
    Join Date
    Jan 2017
    Location
    Swansea,South Wales,UK
    Posts
    4,914
    Why doesn't MS bloody say what references you need in the help system?
    I just copied the code to try it out myself and I do not know what library FileExsists needs?

    Sodding Help gives no clue (well none that I can see)

    https://learn.microsoft.com/en-us/of...mobject-object
    Please use # icon on toolbar when posting code snippets.
    Cross Posting: https://www.excelguru.ca/content.php?184
    Debugging Access: https://www.youtube.com/results?sear...bug+access+vba

  6. #6
    jimrosser is offline Novice
    Windows 11 Access 2019
    Join Date
    Jan 2023
    Posts
    11
    Code:
    Sub AddRecordsIntoAccessTable()        
        '-----------------------------------------------------------------------------
        'The macro opens the Sample.accdb database and adds the 7 rows from the sheet
        '"Excel Data" in the "Customers" table of the database.
        'The code uses late binding, so no reference to external library is required.
        
        'Written By:    Christos Samaras
        'Date:          27/06/2020
        'E-mail:        xristos.samaras@gmail.com
        'Site:          https://myengineeringworld.net
        '-----------------------------------------------------------------------------
    
    
        'Declaring the necessary variables.
        Dim accessFile  As String
        Dim accessTable As String
        Dim sht         As Worksheet
        Dim lastRow     As Long
        Dim lastColumn  As Integer
        Dim con         As Object
        Dim rs          As Object
        Dim sql         As String
        Dim sql1        As String
        Dim i           As Long
        Dim j           As Integer
        Dim strSheetName As String
        strSheetName = ActiveSheet.Name
                
        'Disable the screen flickering.
        Application.ScreenUpdating = False
        
        'Specify the file path of the accdb file. You can also use the full path of the file like this:
        'AccessFile = "C:\Users\Christos\Desktop\Sample.accdb"
        accessFile = ThisWorkbook.Path & "\" & "Sample.accdb"
             
        'Ensure that the Access file exists.
        If FileExists(accessFile) = False Then
            MsgBox "The Access file doesn't exist!", vbCritical, "Invalid Access file path"
            Exit Sub
        End If
        MsgBox ("Variable = " & strSheetName)
        'Set the name of the table you want to add the data.
        accessTable = strSheetName
        
                    
        'Set the worksheet that contains the data.
        On Error Resume Next
        Set sht = ThisWorkbook.ActiveSheet
        'ThisWorkbook.Sheets("Excel Data")
        If Err.Number <> 0 Then
            MsgBox "The given worksheet does not exist!", vbExclamation, "Invalid Sheet Name"
            Exit Sub
        End If
        Err.Clear
        
    
    
        'Find the last row and last column in the given worksheet.
        With sht
            lastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
            lastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
        End With
        
        'Check if there are data in the worksheet.
        If lastRow < 2 Or lastColumn < 1 Then
            MsgBox "There are no data in the given worksheet!", vbCritical, "Empty Data"
            Exit Sub
        End If
            
        'Create the ADODB connection object.
        Set con = CreateObject("ADODB.connection")
        
        'Check if the object was created.
        If Err.Number <> 0 Then
            MsgBox "The connection was not created!", vbCritical, "Connection Error"
            Exit Sub
        End If
        Err.Clear
        
        'Open the connection.
        con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & accessFile
        
        con.Execute "DELETE * FROM " & accessTable
        
        sql = "SELECT * FROM " & accessTable
        
            
        'Create the ADODB recordset object.
        Set rs = CreateObject("ADODB.Recordset")
        
        'Check if the object was created.
    '    If Err.Number <> 0 Then
    '        Set rs = Nothing
    '        Set con = Nothing
    '        MsgBox "The recordset was not created!", vbCritical, "Recordset Error"
    '        Exit Sub
    '    End If
    '    Err.Clear
        con.Execute "DELETE * FROM " & accessTable
        'Set the necessary recordset properties.
        rs.CursorType = 1   'adOpenKeyset on early binding
        rs.LockType = 3     'adLockOptimistic on early binding
            
        'Open the recordset.
        rs.Open sql, con
        
        con.Execute "DELETE * FROM " & accessTable
         
         
        'Add the records from Excel to Access by looping through the rows and columns of the given worksheet.
        'Here the headers are in the row 1 and they are identical to the Access table headers.
        'This is the reason why, for example, there are no spaces in the headers of the sample worksheet.
        For i = 2 To lastRow
            rs.AddNew
            For j = 1 To lastColumn
                'This is how it will look like the first time (i = 2, j = 1):
                'rs("FirstName") = "Bob"
                rs(sht.Cells(1, j).Value) = sht.Cells(i, j).Value
            Next j
            rs.Update
        Next i
            
        'Close the recordet and the connection.
        rs.Close
        con.Close
        
        'Release the objects.
        Set rs = Nothing
        Set con = Nothing
        
        'Re-enable the screen.
        Application.ScreenUpdating = True
    
    
        'Inform the user that the macro was executed successfully.
        MsgBox lastRow - 1 & " rows were successfully added into the '" & accessTable & "' table!", vbInformation, "Done"
        
    End Sub
    
    
    Function FileExists(FilePath As String) As Boolean
     
        '--------------------------------------------------
        'Checks if a file exists (using the Dir function).
        '--------------------------------------------------
     
        On Error Resume Next
        If Len(FilePath) > 0 Then
            If Not Dir(FilePath, vbDirectory) = vbNullString Then FileExists = True
        End If
        On Error GoTo 0
     
    End Function

  7. #7
    Join Date
    Jan 2017
    Location
    Swansea,South Wales,UK
    Posts
    4,914
    Vlad's code worked for me?

    Code:
    Con.Execute "DELETE * FROM [" & accesstable & "]"
    With or without the brackets.
    Please use # icon on toolbar when posting code snippets.
    Cross Posting: https://www.excelguru.ca/content.php?184
    Debugging Access: https://www.youtube.com/results?sear...bug+access+vba

  8. #8
    Gicu's Avatar
    Gicu is offline VIP
    Windows 10 Access 2010 32bit
    Join Date
    Jul 2015
    Location
    Kelowna, BC, Canada
    Posts
    4,114
    What is the table name? If it has spaces in it you need the square brackets as in my original post....

  9. #9
    jimrosser is offline Novice
    Windows 11 Access 2019
    Join Date
    Jan 2023
    Posts
    11
    I tried it with the brackets and without it reads the code but and doesn't give any error but I don't see the data being deleted from the access tabel.

    Con.Execute "DELETE * FROM [" & accesstable & "]"
    Con.Execute "DELETE * FROM [" & accesstable & "]"

  10. #10
    jimrosser is offline Novice
    Windows 11 Access 2019
    Join Date
    Jan 2023
    Posts
    11
    Customers is the name

  11. #11
    Join Date
    Jan 2017
    Location
    Swansea,South Wales,UK
    Posts
    4,914
    Well perhaps comment out the On Error Resume Next and see what you get?
    Please use # icon on toolbar when posting code snippets.
    Cross Posting: https://www.excelguru.ca/content.php?184
    Debugging Access: https://www.youtube.com/results?sear...bug+access+vba

  12. #12
    jimrosser is offline Novice
    Windows 11 Access 2019
    Join Date
    Jan 2023
    Posts
    11
    it just goes right through the script and says it added 7 records

  13. #13
    Join Date
    Jan 2017
    Location
    Swansea,South Wales,UK
    Posts
    4,914
    Quote Originally Posted by jimrosser View Post
    it just goes right through the script and says it added 7 records
    Did it add 7 records? Don't go by what it says. You wote that code remember.
    I tend to check?, so when I deleted the records, I went into the table to make sure they were deleted.
    Please use # icon on toolbar when posting code snippets.
    Cross Posting: https://www.excelguru.ca/content.php?184
    Debugging Access: https://www.youtube.com/results?sear...bug+access+vba

  14. #14
    jimrosser is offline Novice
    Windows 11 Access 2019
    Join Date
    Jan 2023
    Posts
    11
    Thanks for he help! - probably too much error handling going on. I rewrote the portion of the code to just delete the table.
    Code:
    Sub Example1()'Access object
        Dim appAccess As Object
        Dim accessFile  As String
        Dim accessTable As String
        Dim sht         As Worksheet
        Dim lastRow     As Long
        Dim lastColumn  As Integer
        Dim con         As Object
        Dim rs          As Object
        Dim sql         As String
        Dim sql1        As String
        Dim i           As Long
        Dim j           As Integer
        Dim strSheetName As String
        strSheetName = ActiveSheet.Name
        Set con = CreateObject("ADODB.connection")
        accessFile = "C:\Users\jrosser\Documents\Budget Access\Sample.accdb"
    'create new access object
    Set appAccess = CreateObject("Access.Application")
    'open the acces project
    'Open the connection.
        con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & accessFile
    
    
    accessTable = "Customers"
    con.Execute "DELETE * FROM [" & accessTable & "]"
    
    
    End Sub

  15. #15
    Gicu's Avatar
    Gicu is offline VIP
    Windows 10 Access 2010 32bit
    Join Date
    Jul 2015
    Location
    Kelowna, BC, Canada
    Posts
    4,114
    And I take it worked?

    Cheers,
    Vlad Cucinschi
    MS Access Developer
    http://forestbyte.com/

Page 1 of 2 12 LastLast
Please reply to this thread with any new information or opinions.

Similar Threads

  1. Replies: 5
    Last Post: 09-24-2021, 10:28 AM
  2. deleting multiple records from the table
    By talhaparvaiz@yahoo.com in forum Access
    Replies: 2
    Last Post: 06-27-2020, 02:36 PM
  3. Replies: 10
    Last Post: 01-15-2020, 06:01 AM
  4. Replies: 5
    Last Post: 03-11-2019, 02:35 PM
  5. Replies: 6
    Last Post: 10-07-2014, 03:02 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Other Forums: Microsoft Office Forums