danh said:
I have an excel
spreadsheet and I would like to export it to a table in Access. Can I do that
from Excel
You can use ADO in Excel VBA code to do this. Querying an open
workbook is never a good idea, especially so with ADO, but the
workaround is simple: copy the relevant sheets into a new blank
workbook, save and close it, then query the closed copy. Here's some
sample code:
Sub UpdateRemoteDB()
Dim wb As Excel.Workbook
Dim Con As Object
Dim strConXL As String
Dim strConDB As String
Dim strPathXL As String
Dim strSql1 As String
Dim lngRowsAffected As Long
' Amend the following constants to suit
Const XL_WORKBOOK_TEMP As String = "" & _
"delete_me.xls"
Const XL_SHEET As String = "" & _
"MySheet"
Const DATABASE_PATH_FILENAME As String = "" & _
"C:\MyDatabase.mdb"
Const DATABASE_TABLE As String = "" & _
"MyTable"
' Do NOT amend the following constants
Const CONN_STRING_LOCAL As String = "" & _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=<PATH><FILENAME>;" & _
"Extended Properties='Excel 8.0;HDR=YES'"
Const CONN_STRING_SERVER As String = "" & _
"[database=<PATH_FILENAME>;]"
' Build connection strings
strPathXL = ThisWorkbook.Path & _
Application.PathSeparator
strConXL = CONN_STRING_LOCAL
strConXL = Replace(strConXL, _
"<PATH>", strPathXL)
strConXL = Replace(strConXL, _
"<FILENAME>", XL_WORKBOOK_TEMP)
strConDB = CONN_STRING_SERVER
strConDB = Replace(strConDB, _
"<PATH_FILENAME>", DATABASE_PATH_FILENAME)
' Build sql statement
strSql1 = ""
strSql1 = strSql1 & "INSERT INTO " & strConDB
strSql1 = strSql1 & "." & DATABASE_TABLE
strSql1 = strSql1 & " SELECT * FROM [" & XL_SHEET & "$]"
' Delete old instance of temp workbook
On Error Resume Next
Kill strPathXL & XL_WORKBOOK_TEMP
On Error GoTo 0
' Save copy of worksheet to temp workbook
Set wb = Excel.Application.Workbooks.Add()
With wb
ThisWorkbook.Worksheets(XL_SHEET). _
Copy .Worksheets(1)
.SaveAs strPathXL & XL_WORKBOOK_TEMP
.Close
End With
' Open connection to temp workbook
Set Con = CreateObject("ADODB.Connection")
With Con
.ConnectionString = strConXL
.Open
.Execute strSql1, lngRowsAffected
.Close
End With
Debug.Print lngRowsAffected
End Sub
If you prefer GUI tools you could use MS Query from Excel, however it
is not as user friendly for anything other than SELECT queries. Easier
if you create a stored procedure in the database and pass values as
parameters.
Jamie.
--