I\'ve made some code to insert data from an excel table in to an access database - my code is as follow:
Sub AddData()
Dim Cn As ADODB.Connection
Set C
What happens if you put a $ sign after the sheet name like this [datasheet$] ?
xlFilepath = Application.ThisWorkbook.FullName
Sql = "INSERT INTO tblSales " & _
"SELECT * FROM [Excel 12.0 Macro;HDR=YES;DATABASE=" & xlFilepath & "].[datasheet$A1:AK10011] "
cnn.Execute Sql
Warning in your Datasheet Table The first 8 rows. Assuming theres a Heading (HDR=YES) the next 6 rows should contain a dummy data to define your columns equivalent to your access table column definition.
All that is missing, as far as I can see, is the path to your data source and a string on datasheet:
Data Source=sample.xls;
Should read, for example:
Data Source=c:\docs\sample.xls;
And:
SELECT * FROM [datasheet$]
The SELECT statement runs on the database itself, but you want to send values from EXCEL. So you must use
cn.Execute "INSERT .... VALUES (" & excelcell_or_variable & ");"
eventually in a loop to proces all rows/columns etc.
Hope that helps
good luck
EDIT ... don't forget quotation marks surrounding CHAR's and interpunctations; I use
' ....
' .... "...VALUES (" & T(Q(MyStringCell)) & T(MyNumCell) & Q(MyLastTextCell) & ");"
' ....
' surrounds a string by single quotes
Private Function Q(Arg as String) As String
Q = "'" & Arg & "'"
Return
' appens a comma to a string
Private Function T(Arg as String) As String
T = Arg & ","
Return
EDIT 2 I asume that in EXCEL the values you want to insert into the DB are all in 1 row ...
Suppose you have a source_range which contains more than 1 row, you must fire the INSERT statement for each row in that range. You use the .Rows
property to return a single row from a range. And you send multiple columns to the INSERT statement within the same row by using .Cells(1, 1)
, .Cells(1,2)
.... and so on
example:
Sub Test()
Dim MyRange As Range, MyRow As Range
Set MyRange = Range([B4], [C8]) ' source range
For Each MyRow In MyRange.Rows ' get one row at the time from source range
Debug.Print MyRow.Cells(1, 1), MyRow.Cells(1, 2)
' replace the above by your INSERT statement
Next MyRow
End Sub
I think you cannot execute a query on just any open workbook. It MUST be run against a file, that means you have to provide a full path to you sheet, including the filename. If your workbook is "dirty", you need to save it first. I would rather