When I run Microsoft's example I get an error Undefined Object on the Dim
xlApp As Excel.Application
So I then tried putting in your references and running into all sorts of
issues. Below is what I tried.
Any help would be greatly appreciated.
Thank you in advance,
Michael Kintner
Public Sub WorkArounds()
'On Error GoTo Leave
Dim strSQL As String
Dim SQL As String
Dim XLSFile As String
Dim XLSSheet As String
Dim Db As ADODB.Connection
Set Db = New ADODB.Connection
Db.CursorLocation = adUseClient
Db.Open "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data
Source=H:\MySystem\Desktop\Projects\Access-Excel\AccessExcel.mdb"
'*Note: In Office Access 2007, use the following line of code:
'Db.Open "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source=<AccessPath>"
XLSFile = "H:\MySystem\Desktop\Projects\Access-Excel\BuildXLSData.xls"
XLSSheet = "Prep_Viscosity"
SQL = "Select * from TestUpdate"
Call CopyRecordSetToXL(XLSFile, XLSSheet, SQL, Db)
Db.Close
MsgBox "Access has successfully exported the data to excel file.",
vbInformation, "Export Successful."
Exit Sub
Leave:
MsgBox Err.Description, vbCritical, "Error"
Exit Sub
End Sub
Private Sub CopyRecordSetToXL(stFile As String, stSheet As String, SQL As
String, con As ADODB.Connection)
Dim rs As New ADODB.Recordset
Dim x
Dim i As Integer, y As Integer
Dim xlApp As Object
'Set xlApp = CreateObject("Excel.Application")
Dim xlwbBook As Object
'Set xlwbBook = CreateObject("Excel.Workbook")
Dim xlwbAddin As Object
'Set xlwbAddin = CreateObject("Excel.Workbook")
Dim xlwsSheet As Object
'Set xlwsSheet = CreateObject("Excel.Worksheet")
Dim rnData As Object
'Set rnData = CreateObject("Excel.Range")
'Dim xlApp As Excel.Application
'Dim xlwbBook As Excel.Workbook, xlwbAddin As Excel.Workbook
'Dim xlwsSheet As Excel.Worksheet
'Dim rnData As Excel.Range
Dim stAddin As String
'Dim rng As Range
Dim rng As Object
'Set rng = CreateObject("Range")
'Instantiate a new session with the COM-Object Excel.exe.
'Set xlApp = New Excel.Application
Set xlApp = CreateObject("Excel.Application")
Set xlwbBook = xlApp.Workbooks.Open(stFile)
Set xlwsSheet = xlwbBook.Worksheets(stSheet)
xlwsSheet.Activate
'Getting the first cell to input the data.
xlwsSheet.Cells.SpecialCells(xlCellTypeLastCell).Select
y = xlApp.ActiveCell.Column - 1
xlApp.ActiveCell.Offset(1, -y).Select
x = xlwsSheet.Application.ActiveCell.Cells.Address
'Opening the recordset based on the SQL query and saving the data in the
Excel worksheet.
rs.CursorLocation = adUseClient
If rs.State = adStateOpen Then
rs.Close
End If
rs.Open SQL, con
If rs.RecordCount > 0 Then
rs.MoveFirst
x = Replace(x, "$", "")
y = Mid(x, 2)
Set rng = xlwsSheet.Range(x)
xlwsSheet.Range(x).CopyFromRecordset rs
End If
xlwbBook.Close True
xlApp.Quit
Set xlwsSheet = Nothing
Set xlwbBook = Nothing
Set xlApp = Nothing
End Sub