Insert records from excel to access - excel

I have a command button in excel to insert the records to access table. Here's my vba code.
Option Explicit
Sub AddRecordsIntoAccessTable()
Dim accessFile As String
Dim accessTable As String
Dim sht As Worksheet
Dim lastRow As Long
Dim lastColumn As Integer
Dim con As Object
Dim rs As Object
Dim sql As String
Dim i As Long
Dim j As Integer
'Disable the screen flickering.
Application.ScreenUpdating = False
'Specify the file path of the accdb file. You can also use the full path of the file like this:
'AccessFile = "C:\Users\Christos\Desktop\Sample.accdb"
accessFile = ThisWorkbook.Path & "\" & "Database daily activity - Beta 6.accdb"
'Ensure that the Access file exists.
If FileExists(accessFile) = False Then
MsgBox "The Access file doesn't exist!", vbCritical, "Invalid Access file path"
Exit Sub
End If
'Set the name of the table you want to add the data.
accessTable = "DAILY_ACTIVITY"
'Set the worksheet that contains the data.
On Error Resume Next
Set sht = ThisWorkbook.Sheets("Daily Activity")
If Err.Number <> 0 Then
MsgBox "The given worksheet does not exist!", vbExclamation, "Invalid Sheet Name"
Exit Sub
End If
Err.Clear
'Find the last row and last column in the given worksheet.
With sht
lastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
lastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
'Check if there are data in the worksheet.
If lastRow < 2 Or lastColumn < 1 Then
MsgBox "There are no data in the given worksheet!", vbCritical, "Empty Data"
Exit Sub
End If
'Create the ADODB connection object.
Set con = CreateObject("ADODB.connection")
'Check if the object was created.
If Err.Number <> 0 Then
MsgBox "The connection was not created!", vbCritical, "Connection Error"
Exit Sub
End If
Err.Clear
'Open the connection.
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & accessFile
'Create the SQL statement to retrieve the table data (the entire table).
sql = "SELECT * FROM " & accessTable
'Create the ADODB recordset object.
Set rs = CreateObject("ADODB.Recordset")
'Check if the object was created.
If Err.Number <> 0 Then
Set rs = Nothing
Set con = Nothing
MsgBox "The recordset was not created!", vbCritical, "Recordset Error"
Exit Sub
End If
Err.Clear
'Set the necessary recordset properties.
rs.CursorType = 1 'adOpenKeyset on early binding
rs.LockType = 3 'adLockOptimistic on early binding
'Open the recordset.
rs.Open sql, con
'Add the records from Excel to Access by looping through the rows and columns of the given worksheet.
'Here the headers are in the row 1 and they are identical to the Access table headers.
'This is the reason why, for example, there are no spaces in the headers of the sample worksheet.
For i = 2 To lastRow
rs.AddNew
For j = 1 To lastColumn
'This is how it will look like the first time (i = 2, j = 1):
'rs("FirstName") = "Bob"
rs(sht.Cells(1, j).Value) = sht.Cells(i, j).Value
Next j
rs.Update
Next i
'Close the recordet and the connection.
rs.Close
con.Close
'Release the objects.
Set rs = Nothing
Set con = Nothing
'Re-enable the screen.
Application.ScreenUpdating = True
'Inform the user that the macro was executed successfully.
MsgBox lastRow - 1 & " rows were successfully added into the '" & accessTable & "' table!", vbInformation, "Done"
End Sub
Function FileExists(FilePath As String) As Boolean
'--------------------------------------------------
'Checks if a file exists (using the Dir function).
'--------------------------------------------------
On Error Resume Next
If Len(FilePath) > 0 Then
If Not Dir(FilePath, vbDirectory) = vbNullString Then FileExists = True
End If
On Error GoTo 0
End Function
As an example, I create 2 records in excel. It says that those 2 rows had successfully added into my access table. Yet, the added rows are not found in the access table.
Is there something to do in how I linked the excel and access?

Related

VBA: How to delete Queries from active worksheet?

I have a Workbook that has a "live" tab, which has around 8 Queries.
Everyday I duplicate this sheet, before refreshing. In the duplicated sheet, I would like to remove all queries, as i dont need them anymore.
I'm trying to create a macro to remove all Queries.
I tried following code, but it doesn't work. error: object doesn't support this method for the line 5.
Sub DelQueries()
Dim q As WorkbookQuery
For Each q In ActiveWorkbook.Queries
If q.Parent.Name = ActiveSheet.Name Then
q.Delete
End If
Next
End Sub
I also tried the code from this question, with some modification, but gets syntax error for line 3.
Sub loop_del_query()
For Each Worksheet In ThisWorkbook.Worksheets
If Worksheet.Name = ActiveSheet.Name
Qcount = Worksheet.Queries.Count
If Qcount > 0 Then
For Each Query In Worksheet.Queries
Query.Delete
Next
End If
End If
Next Worksheet
End Sub
As explained on this post try ;
Option Explicit
Sub DeleteQueries()
Dim wb As Workbook, ws As Worksheet
Dim wq As WorkbookQuery, qname As String
Dim qt As QueryTable, tbl As ListObject
Dim msg As String, dict As Object
Set dict = CreateObject("Scripting.Dictionary")
Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet1")
' existing queries
For Each wq In wb.Queries
dict.Add wq.Name, 1
Next
' scan table object for query tables
For Each tbl In ws.ListObjects
Set qt = Nothing
On Error Resume Next
Set qt = tbl.QueryTable
On Error GoTo 0
If Not qt Is Nothing Then
qname = qt.WorkbookConnection.Name
If Left(qname, 8) = "Query - " Then
qname = Mid(qname, 9)
'Debug.Print tbl.Name & " Query:" & qname
'delete query if exists
If dict.exists(qname) Then
wb.Queries(qname).Delete
msg = msg & vbCrLf & qname
Else
Debug.Print "Not found", qname
End If
End If
End If
Next
If msg = "" Then
MsgBox "No Queries deleted", vbInformation
Else
MsgBox "Queries deleted:" & msg, vbInformation
End If
End Sub

if duplicate update, else add records (from excel to access)

I have a command button in excel to insert the records to access table. Here's my vba code.
Option Explicit
Sub AddRecordsIntoAccessTable()
Dim accessFile As String
Dim accessTable As String
Dim sht As Worksheet
Dim lastRow As Long
Dim lastColumn As Integer
Dim con As Object
Dim rs As Object
Dim sql As String
Dim i As Long
Dim j As Integer
'Disable the screen flickering.
Application.ScreenUpdating = False
'Specify the file path of the accdb file. You can also use the full path of the file like this:
'AccessFile = "C:\Users\Christos\Desktop\Sample.accdb"
accessFile = ThisWorkbook.Path & "\" & "Database daily activity.accdb"
'Ensure that the Access file exists.
If FileExists(accessFile) = False Then
MsgBox "The Access file doesn't exist!", vbCritical, "Invalid Access file path"
Exit Sub
End If
'Set the name of the table you want to add the data.
accessTable = "DAILY_ACTIVITY"
'Set the worksheet that contains the data.
On Error Resume Next
Set sht = ThisWorkbook.Sheets("Daily Activity")
If Err.Number <> 0 Then
MsgBox "The given worksheet does not exist!", vbExclamation, "Invalid Sheet Name"
Exit Sub
End If
Err.Clear
'Find the last row and last column in the given worksheet.
With sht
lastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
lastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
'Check if there are data in the worksheet.
If lastRow < 2 Or lastColumn < 1 Then
MsgBox "There are no data in the given worksheet!", vbCritical, "Empty Data"
Exit Sub
End If
'Create the ADODB connection object.
Set con = CreateObject("ADODB.connection")
'Check if the object was created.
If Err.Number <> 0 Then
MsgBox "The connection was not created!", vbCritical, "Connection Error"
Exit Sub
End If
Err.Clear
'Open the connection.
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & accessFile
'Create the SQL statement to retrieve the table data (the entire table).
sql = "SELECT * FROM " & accessTable
'Create the ADODB recordset object.
Set rs = CreateObject("ADODB.Recordset")
'Check if the object was created.
If Err.Number <> 0 Then
Set rs = Nothing
Set con = Nothing
MsgBox "The recordset was not created!", vbCritical, "Recordset Error"
Exit Sub
End If
Err.Clear
'Set the necessary recordset properties.
rs.CursorType = 1 'adOpenKeyset on early binding
rs.LockType = 3 'adLockOptimistic on early binding
'Open the recordset.
rs.Open sql, con
'Add the records from Excel to Access by looping through the rows and columns of the given worksheet.
'Here the headers are in the row 1 and they are identical to the Access table headers.
'This is the reason why, for example, there are no spaces in the headers of the sample worksheet.
Application.ScreenUpdating = True
On Error GoTo 0
For i = 2 To lastRow
rs.AddNew
For j = 1 To lastColumn
'This is how it will look like the first time (i = 2, j = 1):
rs(sht.Cells(1, j).Value) = sht.Cells(i, j).Value
Next j
rs.Update
Next i
'Close the recordet and the connection.
rs.Close
con.Close
'Release the objects.
Set rs = Nothing
Set con = Nothing
'Re-enable the screen.
Application.ScreenUpdating = True
'Inform the user that the macro was executed successfully.
MsgBox lastRow - 1 & " rows were successfully added into the '" & accessTable & "' table!", vbInformation, "Done"
End Sub
Function FileExists(FilePath As String) As Boolean
'--------------------------------------------------
'Checks if a file exists (using the Dir function).
'--------------------------------------------------
On Error Resume Next
If Len(FilePath) > 0 Then
If Not Dir(FilePath, vbDirectory) = vbNullString Then FileExists = True
End If
On Error GoTo 0
End Function
This code can only add new records, and it will be error if there is duplicate.
How do I fix the code with the condition:
Update existing access table for the records that is duplicate.
Add the records that is non duplicate
Could do a Find on recordset to determine if data already exists. If it does, focus will be on that record, otherwise pointer will be at recordset EOF.
For i = 2 To lastRow
rs.Find "some field=" & cell reference, , , 1
If rs.EOF Then
rs.AddNew
Else
rs.Edit
End If
For j = 1 To lastColumn
'This is how it will look like the first time (i = 2, j = 1):
rs(sht.Cells(1, j).Value) = sht.Cells(i, j).Value
Next j
rs.Update
Next i

ListObjects creation - late binding - From Access to Excel

I want to create a table after dropping the data in to a worksheet.
The following code drop a query result from Access to Excel. The code works fine up to "xlSheet.Range("$A$1:$U$2").Select" but failed to create the table. Can you help me?
Option Compare Database
'Use Late Bingding befor move on prod remove Excel ref
Dim xlApp As Object
Dim xlBook As Object
Dim xlSheet As Object
Dim xlTable As Object
'End of late Binding
Sub testExport()
Dim QryName As String
QryName = "BOM_REPORT_UNION"
ExportToExcelUsingQryName (QryName)
End Sub
Sub ExportToExcelUsingQryName(QueryName As String)
On Error GoTo SubError
'Late Binding
Set xlApp = CreateObject("Excel.Application")
'Late Binding end
Dim SQL As String
Dim i As Integer
'Show user work is being performed
DoCmd.Hourglass (True)
'Get the SQL for the queryname and Execute query and populate recordset
SQL = CurrentDb.QueryDefs(QueryName).SQL
Set rsBOMTopDown = CurrentDb.OpenRecordset(SQL, dbOpenSnapshot)
'If no data, don't bother opening Excel, just quit
If rsBOMTopDown.RecordCount = 0 Then
MsgBox "No data selected for export", vbInformation + vbOKOnly, "No data exported"
GoTo SubExit
End If
'*********************************************
' BUILD SPREADSHEET
'*********************************************
'Create an instance of Excel and start building a spreadsheet
xlApp.Visible = False
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets(1)
'Set column heading from recordset
SetColumnHeadingFromRecordset
'Copy data from recordset to Worksheet
xlSheet.Range("A2").CopyFromRecordset rsBOMTopDown
'Create Table
xlSheet.Range("$A$1:$U$2").Select
'Set xlTable = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes).Name = "tblBOMTopDown" ' error 424 - Object Required
'Set xlTable = xlBook.xlSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes).Name = "tblBOMTopDown" ' error 424 - Object Required
Set xlTable = xlSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes) ' error 5 invalid procedure call or argument
'Set xlTable = xlSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes).Name = "tblBOMTopDown"
SubExit:
On Error Resume Next
DoCmd.Hourglass False
xlApp.Visible = True
rsBOMTopDown.Close
Set rsBOMTopDown = Nothing
Exit Sub
SubError:
MsgBox "Error Number: " & Err.Number & "= " & Err.description, vbCritical + vbOKOnly, _
"An error occurred"
GoTo SubExit
End Sub
Sub SetColumnHeadingFromRecordset() '(ByVal xlSheet As Object, rsBOMTopDown As Recordset)
For cols = 0 To rsBOMTopDown.Fields.count - 1
xlSheet.Cells(1, cols + 1).Value = rsBOMTopDown.Fields(cols).Name
Next
End Sub
The proposal from YowE3K did solve my issued. Thank for the help
Here the new code
Option Compare Database
'Use Late Bingding befor move on prod remove Excel ref
Dim xlApp As Object
Dim xlBook As Object
Dim xlSheet As Object
Dim xlTable As Object
'End of late Binding
'XlListObjectSourceType Enumeration (Excel) for late Binding
'Info: https://msdn.microsoft.com/en-us/library/office/ff820815.aspx
'-------------------------------------------------------------------
Public Const gclxlSrcRange As Long = 1 'Range
Sub testExport()
Dim QryName As String
QryName = "BOM_REPORT_UNION"
ExportToExcelUsingQryName (QryName)
End Sub
Sub ExportToExcelUsingQryName(QueryName As String)
On Error GoTo SubError
'Late Binding
Set xlApp = CreateObject("Excel.Application")
'Late Binding end
Dim SQL As String
Dim i As Integer
'Show user work is being performed
DoCmd.Hourglass (True)
'Get the SQL for the queryname and Execute query and populate recordset
SQL = CurrentDb.QueryDefs(QueryName).SQL
Set rsBOMTopDown = CurrentDb.OpenRecordset(SQL, dbOpenSnapshot)
'If no data, don't bother opening Excel, just quit
If rsBOMTopDown.RecordCount = 0 Then
MsgBox "No data selected for export", vbInformation + vbOKOnly, "No data exported"
GoTo SubExit
End If
'*********************************************
' BUILD SPREADSHEET
'*********************************************
'Create an instance of Excel and start building a spreadsheet
xlApp.Visible = False
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets(1)
'Set column heading from recordset
SetColumnHeadingFromRecordset
'Copy data from recordset to Worksheet
xlSheet.Range("A2").CopyFromRecordset rsBOMTopDown
'Create Table
xlSheet.Range("$A$1:$U$2").Select
Set xlTable = xlSheet.ListObjects.Add(gclxlSrcRange, xlApp.Selection, , xlYes)
xlTable.Name = "tblBOMTopDown"
SubExit:
On Error Resume Next
DoCmd.Hourglass False
xlApp.Visible = True
rsBOMTopDown.Close
Set rsBOMTopDown = Nothing
Exit Sub
SubError:
MsgBox "Error Number: " & Err.Number & "= " & Err.description, vbCritical + vbOKOnly, _
"An error occurred"
GoTo SubExit
End Sub
Sub SetColumnHeadingFromRecordset() '(ByVal xlSheet As Object, rsBOMTopDown As Recordset)
For cols = 0 To rsBOMTopDown.Fields.count - 1
xlSheet.Cells(1, cols + 1).Value = rsBOMTopDown.Fields(cols).Name
Next
End Sub

copyfromrecordset returns blank column

I am creating an ADODB connection to a Sybase database, executing an SQL statement into a recordset, and then using the CopyFromRecordset method to paste the contents of the recordset to a range. This has been working fine but I recently moved PC's at work and now one of the columns is returning nothing.
When I run the same SQL in SQuirreL the column is not blank.
If I pause the VBA and try to look at one of the values in the column / field in question (ie ?rst.fields(1).value in the immediate Window) I get the following error message:
Run-time error '-2147467259 (80004005)': Unspecified error.
In the Squirrel results Metadata tab the column in question is described as:
ColumnIndex 2
getColumnName CommentText
getColumnTypeName text
getPrecision 2147483647
getScale 0
isNullable 0
getTableName xxxxxxx
getSchemaName
getCatalogName
getColumnClassName java.sql.Clob
getColumnDisplaySize 2147483647
getColumnLabel CommentText
getColumnType 2005
isAutoIncrement FALSE
isCaseSensitive FALSE
isCurrency FALSE
isDefinitelyWritable FALSE
isReadOnly FALSE
isSearchable FALSE
isSigned FALSE
isWritable TRUE
The code in question is below, but, as stated the code does not seem to be the problem as it has worked previously - any ideas?
Sub ImportComments()
Dim wsData As Worksheet
Dim rng As Range
Dim cn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim x As Long
Dim rngSQL As Range
Dim cell As Range
Dim sSQL As String
Dim sProvider As String
Dim sDS As String
Dim sDataSource As String
Dim sUser As String
Dim sCatalog As String
Dim sPassword As String
Dim rngDS As Range
Dim rngThisDS As Range
Dim sConnect As String
Dim sInstance As String
Dim fSuccess As Boolean
Dim sError As String
On Error GoTo ProcExit
'delete previous comments if they exist
If SheetExists("Comments_Data_Import", ThisWorkbook) = True Then
Application.DisplayAlerts = False
ThisWorkbook.Sheets("Comments_Data_Import").Delete
Application.DisplayAlerts = True
End If
'create comments sheet
Set wsData = ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Sheets("EWI_Data_Import"))
wsData.Name = "Comments_Data_Import"
'build sql string
Set rngSQL = Range(ThisWorkbook.Sheets("SQL").Range("A2"), _
ThisWorkbook.Sheets("SQL").Range("A2").End(xlDown))
For Each cell In rngSQL
sSQL = sSQL & cell.Value & " "
Next cell
'define login components
Set rngDS = ThisWorkbook.Worksheets("Login").Range("rngInstance").CurrentRegion
Set rngDS = rngDS.Offset(1, 0).Resize(rngDS.Rows.Count - 1)
sProvider = "Provider=ASEOLEDB.1;"
sUser = "User ID=" & ThisWorkbook.Worksheets("Login").Range("rngUsername").Value & ";"
sPassword = "Password=" & ThisWorkbook.Worksheets("Login").Range("rngPassword").Value
'try to log in to each instance exiting when succesful
Set cn = New ADODB.Connection
cn.CommandTimeout = 600
'turn off error hadling to allow for connection errors On Error Resume Next
For Each rngThisDS In rngDS.Rows
'complete connect string
Err = 0
sInstance = rngThisDS.Cells(1, 1)
sDS = "Data Source=" & rngThisDS.Cells(1, 2) & ";"
sCatalog = "Initial Catalog=" & rngThisDS.Cells(1, 3) & ";"
sConnect = sProvider & sDS & sUser & sCatalog & sPassword
'attempt to open
cn.Open sConnect
'If successful Then
If Err = 0 Then
'flag success
fSuccess = True
'execute SQL
On Error GoTo ProcError
Set rst = cn.Execute(sSQL)
'copy data into comments sheet
wsData.Range("A2").CopyFromRecordset rst
'Put in the headers
Set rng = wsData.Range("A1")
For x = 1 To rst.Fields.Count
rng.Offset(0, x - 1).Value = rst.Fields(x - 1).Name
Next x
FormatComments
Exit For
End If
Next rngThisDS
If fSuccess = False Then
MsgBox ("Unable to connect to Insight")
Else
MsgBox "Connected to and exported data from " & sInstance
End If
ProcExit:
Set wsData = Nothing
Set rng = Nothing
Set cn = Nothing
Set rst = Nothing
Set rngSQL = Nothing
Set cell = Nothing
Set rngDS = Nothing
Set rngThisDS = Nothing
Exit Sub
ProcError:
MsgBox "Error: " & Err.Description
Resume ProcExit
End Sub
According to the CopyFromRecordset() MSDN:
When this method copies the recordset to the worksheet, the results
will be truncated if you do not specify a range that is large enough
to hold the contents of the recordset.
Consider specifying the range with MoveFirst command reset:
' Copy data into comments sheet
rst.MoveLast
rst.MoveFirst
wsData.Range("A2:Z500").CopyFromRecordset rst
Or entire worksheet (starting at A1, of course inserting row for column headers)
wsData.Cells.CopyFromRecordset rst
But even then, CopyFromRecordset() is sensitive to data and cursory types even memory (since you pull all data and dump at once), so consider altogether replacing the method and iterate through records for the rows. Even other languages (PHP, Python, Java, etc.) run queries this way, opening cursor and iterating through resultset.
' Put in the headers
Set rng = wsData.Range("A1")
For x = 1 To rst.Fields.Count
rng.Offset(0, x - 1).Value = rst.Fields(x - 1).Name
Next x
' Put in rows
Dim col As Integer, row As Integer
rst.MoveLast
rst.MoveFirst
Set rng = wsData.Range("A2")
row = 0
Do While Not rst.EOF
For col = 0 To rst.Fields.Count - 1
rng.Offset(row, col).Value = rst(col)
Next col
row = row + 1
rst.MoveNext
Loop

How to Export All the data of listview with its header to excel sheet in vb 6.0

I am exporting all the data of a ListView control to an Excel sheet, in VB 6.0.
My code is below:
Private Sub cmdExport_Click()
'general
Dim objExcel As New Excel.Application
Dim objExcelSheet As Excel.Worksheet
'-----------------------------------
'check whether data is there
If LstLog.ListItems.count > 0 Then
objExcel.Workbooks.Add
Set objExcelSheet = objExcel.Worksheets.Add
For Col = 1 To LstLog.ColumnHeaders.count
objExcelSheet.Cells(1, Col).Value = LstLog.ColumnHeaders(Col)
Next
For Row = 2 To LstLog.ListItems.count
For Col = 1 To LstLog.ColumnHeaders.count
If Col = 1 Then
objExcelSheet.Cells(Row, Col).Value = LstLog.ListItems(Row).Text
Else
objExcelSheet.Cells(Row, Col).Value = LstLog.ListItems(Row).SubItems(Col - 1)
End If
Next
Next
objExcelSheet.Columns.AutoFit
CommonDialog1.ShowOpen
A = CommonDialog1.FileName
objExcelSheet.SaveAs A & ".xls"
MsgBox "Export Completed", vbInformation, Me.Caption
objExcel.Workbooks.Open A & ".xls"
objExcel.Visible = True
'objExcel.Quit
Else
MsgBox "No data to export", vbInformation, Me.Caption
End If
End Sub
The problem is that the first row from the ListView is covered by text from the ListView header.
You are not copying all the rows, for some reason. Try this:
For Row = 2 To LstLog.ListItems.count + 1
For Col = 1 To LstLog.ColumnHeaders.count
If Col = 1 Then
objExcelSheet.Cells(Row, Col).Value = LstLog.ListItems(Row - 1).Text
Else
objExcelSheet.Cells(Row, Col).Value = LstLog.ListItems(Row - 1).SubItems(Col - 1)
End If
Next
Next Row
Try this hope this will help u
Function Export2XLS(sQuery As String)
Dim oExcel As Object
Dim oExcelWrkBk As Object
Dim oExcelWrSht As Object
Dim bExcelOpened As Boolean
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim iCols As Integer
Const xlCenter = -4108
'Start Excel
On Error Resume Next
Set oExcel = GetObject(, "Excel.Application") 'Bind to existing instance of Excel
If Err.Number <> 0 Then 'Could not get instance of Excel, so create a new one
Err.Clear
On Error GoTo Error_Handler
Set oExcel = CreateObject("excel.application")
bExcelOpened = False
Else 'Excel was already running
bExcelOpened = True
End If
On Error GoTo Error_Handler
oExcel.ScreenUpdating = False
oExcel.Visible = False 'Keep Excel hidden until we are done with our manipulation
Set oExcelWrkBk = oExcel.Workbooks.Add() 'Start a new workbook
Set oExcelWrSht = oExcelWrkBk.Sheets(1)
'Open our SQL Statement, Table, Query
Set db = CurrentDb
Set rs = db.OpenRecordset(sQuery, dbOpenSnapshot)
With rs
If .RecordCount <> 0 Then
'Build our Header
For iCols = 0 To rs.Fields.Count - 1
oExcelWrSht.Cells(1, iCols + 1).Value = rs.Fields(iCols).Name
Next
With oExcelWrSht.Range(oExcelWrSht.Cells(1, 1), _
oExcelWrSht.Cells(1, rs.Fields.Count))
.Font.Bold = True
.Font.ColorIndex = 2
.Interior.ColorIndex = 1
.HorizontalAlignment = xlCenter
End With
oExcelWrSht.Range(oExcelWrSht.Cells(1, 1), _
oExcelWrSht.Cells(1, rs.Fields.Count)).Columns.AutoFit 'Resize our Columns based on the headings
'Copy the data from our query into Excel
oExcelWrSht.Range("A2").CopyFromRecordset rs
oExcelWrSht.Range("A1").Select 'Return to the top of the page
Else
MsgBox "There are no records returned by the specified queries/SQL statement.", vbCritical + vbOKOnly, "No data to generate an Excel spreadsheet with"
GoTo Error_Handler_Exit
End If
End With
' oExcelWrkBk.Close True, sFileName 'Save and close the generated workbook
' 'Close excel if is wasn't originally running
' If bExcelOpened = False Then
' oExcel.Quit
' End If
Error_Handler_Exit:
On Error Resume Next
oExcel.Visible = True 'Make excel visible to the user
rs.Close
Set rs = Nothing
Set db = Nothing
Set oExcelWrSht = Nothing
Set oExcelWrkBk = Nothing
oExcel.ScreenUpdating = True
Set oExcel = Nothing
Exit Function
Error_Handler:
MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: Export2XLS" & vbCrLf & _
"Error Description: " & Err.Description _
, vbOKOnly + vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit
End Function

Resources