You are here:

Excel/Adding on Error resume next


Hey Aidan,

Greetings of the day.

I have an macro that is updating values from excel to Access. In Access database I have defined a primary key that prevents any duplicate entries to be entered in the database.

The issue that I am facing is , as soon as any duplicate entry comes, macro simply ends rather than skipping the entry and moving the next record. Please suggest a way out for this.

my macro looks like this :

Sub print()
Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long
Dim x, i As Long

' connect to the Access database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; " & _
   "Data Source=test.accdb;"
' open a recordset
Set rs = New ADODB.Recordset
rs.Open "Dhwani", cn, adOpenKeyset, adLockOptimistic, adCmdTable
' all records in a table
'For i = 1 To 2
   'x = 0
   'i = 2
   x = 2
   i = 2
      Do While Not IsEmpty(Range("A" & x))

'Do While Len(Range("A" & x).Offset(0, x).Formula) > 0
' repeat until first empty cell in column A
       With rs
         .AddNew ' create a new record
         .Fields("Name") = Range("A" & i).Value
         .Fields("Rollno") = Range("B" & i).Value      
        ' stores the new record
   End With
   x = x + 1
   i = i + 1
'Next i
Set rs = Nothing
Set cn = Nothing

End Sub

resume next will simply skip the error without recording anything - assuming this is what is needed, put the line anywhere towards the top of the macro - I would suggest

Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long
Dim x, i As Long
On Error Resume Next
' connect to the Access database

and it should then work fine - I created a test database and ran the macro to make sure and got the desired result.
About Excel
This topic answers questions related to Microsoft Excel spreadsheet (or workbook) stand-alone or Mircrosoft Office Excel including Excel 2003, Excel 2007, Office 2000, and Office XP. You can get Excel help on Excel formulas(or functions), Excell macros, charting in Excel, advanced features, and the general use of Excel. This does not provide a general Excel tutorial nor the basics of using a spreadsheet. It provides specific answers to using Microsoft Excel only. If you do not see your Excel question answered in this area then please ask an Excel question here


All Answers

Answers by Expert:

Ask Experts


Aidan Heritage


I have provided first hand support since `95 for Microsoft Office majoring in Word and Excel - support for all versions from 2 onwards. I'm based in the UK, so please allow for time differences when asking me questions from other parts of the world!


My background is in the insurance industry and call centre areas, but have been called upon to provide many varied solutions.

I'm educated to UK A level standard, but as I left school some 30 years ago that is rather irrelevent - university of life has provided more of a background!

©2016 All rights reserved.