Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

I am using the following code to ex

Status
Not open for further replies.

simoncpage

Programmer
Apr 4, 2002
256
GB
I am using the following code to export data to excel. WHat I want to do is change this so that it works for a certain number of columns. For instance say three columns D, E, and F. But Ideally I would like to put in a for...next statement so that I can vary the number of columns rather than just the one as in my code - range("A") any ideas on this anyone???


----------------------------
Sub ADOFromExcelToAccess()
' 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.Jet.OLEDB.4.0; Data Source=C:\FolderName\DataBaseName.mdb;"
' open a recordset
Set rs = New ADODB.Recordset
rs.Open "TableName", cn, adOpenKeyset, adLockOptimistic, adCmdTable ' all records in a table
r = 3 ' the start row in the worksheet
Do While Len(Range("A" & r).Formula) > 0 ' repeat until first empty cell in column A
With rs
.AddNew ' create a new record
' add values to each field in the record
.Fields("FieldName1") = Range("A" & r).Value
.Fields("FieldName2") = Range("B" & r).Value
.Fields("FieldNameN") = Range("C" & r).Value
' add more fields if necessary...
.Update ' stores the new record
End With
r = r + 1 ' next row
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
 
Hi,simoncpage,

Does ALL your data from the sheet get processed?

If YES then
set rng = cells(1,1).currentregion
with rng
lRowCount = .Rows.Count
iColCount = .Columns.Count
end with
for each r in rng
select case r.column
case 1
rs .Fields("FieldName1") =r.Value
case 2
rs .Fields("FieldName2") =r.Value
.....
end select
next
[/code]
Hope this helps :) Skip,
metzgsk@voughtaircraft.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top