Excel data to Access

dimsums

New Member
Joined
Jun 29, 2020
Messages
30
Office Version
  1. 365
Platform
  1. Windows
Hi All,
I was wondering if i could get help with this code below. I use it to transfer data from excel to access, However, if there is only one row to transfer it comes in access multiple times. For example, if i have a row to transfer and i hit the button, the row will be copied five times onto the access table.
Please let me know where i am going wrong.
Sub ADOFromExcelToAccess2()
' exports data from the active worksheet to a table in an Access database
' this procedure must be edited before use
Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long
' connect to the Access database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; " & _
"Data Source=C:\Users\smriti.singh\Desktop\Test.accdb;" 'this is where you put the address of the acces file
' open a recordset
Set rs = New ADODB.Recordset
rs.Open "Table1", cn, adOpenKeyset, adLockOptimistic, adCmdTable 'this is where the name of the table is put in, rn it is Table1 we can change it
' all records in a table
For i = 3 To 16 'this is what is taken from the spreadsheet so it will start from row 3 and go to 16
x = 0
Do While Len(Range("E" & i).Offset(0, x).Formula) > 0
' repeat until first empty cell in column A
With rs
.AddNew ' create a new record
.Fields("Nature") = Range("A" & i).Value
.Fields("No") = Range("B" & i).Value
.Fields("NameP") = Range("C" & i).Value
.Update
' stores the new record
End With
x = x + 1
Loop
Next i
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing

End Sub
 

Some videos you may like

Excel Facts

How to create a cell-sized chart?
Tiny charts, called Sparklines, were added to Excel 2010. Look for Sparklines on the Insert tab.

rondeondo

Board Regular
Joined
Aug 15, 2012
Messages
156
The line:
Do While Len(Range("E" & i).Offset(0, x).Formula) > 0
this will cause the insert to happen once for each column that has data in it. The offset makes it count across the columns.
There doesn't seem to be a reason for the loop incrementing x that is referred to in this. Try without this loop. The loop of i will cycle through the rows for you.
 

Watch MrExcel Video

Forum statistics

Threads
1,113,745
Messages
5,543,959
Members
410,586
Latest member
acadavid86
Top