Append to Excel from Access using VBA - excel

With this particular problem I can’t get the code to append the exported data from Access to Excel. I have created an simple Access database with some data shown on a form. After that it is possible to export the shown record to Excel using the code.
So far so good. But when I export the next record it overwrites the previous exported data on row one in Excel. I want the code to append to the next row and so on.
I have found some topics on how to append with “ActiveCell.Value” and “ActiveCell.Offset” but my knowledge is too limited to get it to work with the code. The moment I think I got it, VBE comes with errors. It seems I can't figure this out.
Private Sub Command15_Click()
Dim oExcel As Object
Dim oExcelWrkBk As Object
Dim oExcelWrSht As Object
Dim bExcelOpened As Boolean
'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 oExcelWrkBk = oExcel.Workbooks.Open("C:\test.xlsx") 'Open an existing Excel file
Set oExcelWrSht = oExcelWrkBk.Sheets(1) 'which worksheet to work with
'Start copying over your form values to the Excel Spreadsheet
'Cells(8, 3) = 8th row, 3rd column
oExcelWrSht.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0) = Me.1
oExcelWrSht.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0) = Me.2
oExcelWrSht.Cells(Rows.Count, 3).End(xlUp).Offset(1, 0) = Me.3
oExcelWrSht.Cells(Rows.Count, 4).End(xlUp).Offset(1, 0) = Me.4
oExcelWrSht.Cells(Rows.Count, 5).End(xlUp).Offset(1, 0) = Me.5
oExcelWrSht.Cells(Rows.Count, 6).End(xlUp).Offset(1, 0) = Me.6
oExcelWrSht.Cells(Rows.Count, 7).End(xlUp).Offset(1, 0) = Me.7
oExcelWrSht.Cells(Rows.Count, 8).End(xlUp).Offset(1, 0) = Me.8
oExcelWrSht.Cells(Rows.Count, 9).End(xlUp).Offset(1, 0) = Me.9
'... and so on ...
oExcelWrSht.Range("A1").Select 'Return to the top of the page
' 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
Set oExcelWrSht = Nothing
Set oExcelWrkBk = Nothing
oExcel.ScreenUpdating = True
Set oExcel = Nothing
Exit Sub 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 Sub

I've tried this and no problems so assuming you have a reference to the right excel library can you see if this works?
Sub Test()
Dim oExcel As Excel.Application
Dim oExcelWrkBk As Excel.Workbook
Dim oExcelWrSht As Excel.Worksheet
'Start Excel
On Error Resume Next
Set oExcel = GetObject(, "Excel.Application")
If Err <> 0 Then
Err.Clear
On Error GoTo Error_Handler
Set oExcel = CreateObject("Excel.Application")
Else
On Error GoTo Error_Handler
End If
oExcel.ScreenUpdating = False
oExcel.Visible = False 'This is false by default anyway
Set oExcelWrkBk = oExcel.Workbooks.Open("C:\test.xlsx")
Set oExcelWrSht = oExcelWrkBk.Sheets(1)
oExcelWrSht.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0) = "Test1"
oExcelWrSht.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0) = "Test2"
oExcelWrSht.Cells(Rows.Count, 3).End(xlUp).Offset(1, 0) = "Test3"
oExcelWrSht.Range("A1").Select
oExcelWrkBk.Save
oExcel.ScreenUpdating = True
oExcel.Visible = True
Exit_Point:
Set oExcelWrSht = Nothing
Set oExcelWrkBk = Nothing
Set oExcel = Nothing
Exit Sub
Error_Handler:
MsgBox Err & " - " & Err.Description
GoTo Exit_Point
End Sub

Related

Excel.Application not closed excel file

I want to read some data from excel file and close it.
but my code not closed it:
Function getColumnOfFirstRow(PATH, size) As Long
Dim oApp_Excel As Excel.Application
Dim oBook As Excel.Workbook
Dim column As Long
column = 0
Set oApp_Excel = CreateObject("EXCEL.APPLICATION")
oApp_Excel.DisplayAlerts = False
oApp_Excel.Visible = True
Set oBook = oApp_Excel.Workbooks.Open(PATH, ReadOnly:=True)
On Error GoTo errhand
column = oBook.Sheets("Sheet1").Cells.Find(What:=CStr(size)).column
oBook.Close True
oApp_Excel.Quit
Set oBook = Nothing
errhand:
Select Case Err.Number
Case 91
column = 0
End Select
getColumnOfFirstRow = column
End Function
I think this part of my code must close it:
oBook.Close True
oApp_Excel.Quit
Using a New Instance of Excel
It looks like overkill to open and close Excel and a workbook to just retrieve a number but let's say we're practicing handling objects and error handling.
Function GetSizeColumn(ByVal Path As String, ByVal Size As Double) As Long
On Error GoTo ClearError
Dim xlApp As Excel.Application: Set xlApp = New Excel.Application
xlApp.Visible = True ' out-comment when done testing
Dim wb As Excel.Workbook
Set wb = xlApp.Workbooks.Open(Path, True, True)
Dim SizeColumn As Long
SizeColumn = wb.Sheets("Sheet1").Rows(1).Find(CStr(Size)).Column
' You can avoid the expected error as you have learned in your newer post.
' In this case, if the error occurs, the function will end up with
' its initial value 0 since its result is declared 'As Long'
' i.e. the following line will never be executed.
GetSizeColumn = SizeColumn
ProcExit:
On Error Resume Next
If Not wb Is Nothing Then wb.Close False
If Not xlApp Is Nothing Then xlApp.Quit
On Error GoTo 0
Exit Function
ClearError:
Debug.Print "Run-time error '" & Err.Number & "':" & vbLf & Err.Description
Resume ProcExit
End Function
Try it. 100% working code about creating the excel. In this code, excel converts recordset in excel successfully. After that close the excel successfully. No error.
Also, check with the Task manager and close any excel file open in the process.
Public Sub ConvertRecordSetToExcelFull(Rs As Recordset, _
FileNameWithPath As String, _
SheetName As String, _
Rangename As String)
On Error GoTo Error1
Dim ExlFile As Object, Book As Object, Sheet As Object, K As Long, J As Long
Set ExlFile = CreateObject("Excel.Application")
Set Book = ExlFile.Workbooks.Add
Set Sheet = Book.Worksheets(1)
ExlFile.DisplayAlerts = False
K = 1
For J = 0 To Rs.Fields.Count - 1
Sheet.Cells(K, J + 1) = UCase(Rs.Fields(J).Name)
Next
K = K + 1
If Rs.RecordCount >= 1 Then
'Call RecCount(rs)
Do While Rs.EOF <> True
For J = 0 To Rs.Fields.Count - 1
Sheet.Cells(K, J + 1) = Rs.Fields(J)
Next
K = K + 1
Rs.MoveNext
Loop
End If
Book.Worksheets(1).Name = SheetName
Book.SaveAs FileNameWithPath
ExlFile.ActiveWorkbook.Close False
ExlFile.Quit
Set Sheet = Nothing
Set ExlFile = Nothing
Screen.MousePointer = vbNormal
Exit Sub
Error1:
MsgBox Err.Description
Err.Clear
End Sub

Excel VBA to PPT not working in office 365 64 bit

I was using the below code just fine on all the version of excel
- Basically I created a excel sheet with ppt look and export the sheet range to PPT.
Excel VBA to Export to PPT works fine in all versions till office 365 32bit
Its not working in 365 64 bit, Windows 10 OS
Tried the following
Checked reference - with 14,15,16 object library - works fine..
Not working on 64bit - Excel 365
Error given - "PowerPoint Not found"
Sub ExcelRangeToPPT_new_now()
'prepareppt
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.IgnoreRemoteRequests = True
Dim rng As Range
Dim PowerPointApp As Object
Dim myPresentation As Object
Dim mySlide As Object
Dim myShape As Object
'Sheets("S19").Select
'Copy Range from Excel
Set rng = ThisWorkbook.ActiveSheet.Range("A1:q36")
On Error Resume Next
'Is PowerPoint already opened?
Set PowerPointApp = GetObject(class:="PowerPoint.Application")
'Clear the error between errors
err.Clear
'If PowerPoint is not already open then open PowerPoint
If PowerPointApp Is Nothing Then Set PowerPointApp = CreateObject(class:="PowerPoint.Application")
'Handle if the PowerPoint Application is not found
If err.Number = 429 Then
MsgBox "PowerPoint could not be found, aborting."
Exit Sub
End If
Sheets("template").Select
Set rng = ThisWorkbook.ActiveSheet.Range("A1:q36")
instfile = "Noattach"
If ActFileName = False Then
'PowerPointApp.Activate
'PowerPointApp.Presentations.Add
'Set PP_File = PowerPointApp.ActivePresentation
Else
PowerPointApp.Activate
Set myPresentation = PowerPointApp.Presentations.Open(ActFileName)
End If
Set myPresentation = PowerPointApp.Presentations.Add
Set PP_File = PowerPointApp.ActivePresentation
adddd:
DoEvents
Set rng = ThisWorkbook.ActiveSheet.Range("A1:q36")
PowerPointApp.Visible = True
'Create a New Presentation
rrr:
err.Clear
Set mySlide = PP_File.Slides.Add(1, 12) '11 = ppLayoutTitleOnly
PP_File.Slides (PPApp.ActiveWindow.Selection.SlideRange.SlideIndex)
With PP_File.PageSetup
.SlideSize = ppSlideSizeCustom
.SlideWidth = 720
.SlideHeight = 528
.FirstSlideNumber = 1
.SlideOrientation = msoOrientationHorizontal
.NotesOrientation = msoOrientationVertical
End With
rng.Copy
mySlide.Shapes.PasteSpecial DataType:=2 '2 = ppPasteEnhancedMetafile
Set myShape = mySlide.Shapes(mySlide.Shapes.Count)
'Set position:
myShape.Left = 0
myShape.Top = 0
myShape.LockAspectRatio = msoFalse
myShape.HEIGHT = 528
myShape.WIDTH = 718
If instfile <> "Noattach" Then
Dim objPPTShape As Object
Set objPPTShape = PP_File.Slides(1).Shapes.AddOLEObject(Left:=100, Top:=100, WIDTH:=700, HEIGHT:=300, _
filename:=instfile, DisplayAsIcon:=True) 'OR Use , Filename:="E:\Documents and Settings\User\My Documents\abc.xlsm" instead of ClassName but not both
With objPPTShape
.Left = 475
.Top = 350
End With
Set objPPTShape = Nothing
End If
PowerPointApp.Visible = True
PowerPointApp.Activate
Application.CutCopyMode = False
PowerPointApp.PageSetup.SlideOrientation = msoOrientationHorizontal
sht = sht - 1
If sht = 1 Then Sheets("template").Select: GoTo ttre
instfile = "Noattach"
If sht = 2 Then Sheets("S2").Select: GoTo adddd
ttre:
Sheets("main").Select
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.IgnoreRemoteRequests = False
MsgBox "PPT Created Sucessfully.. Kindly review it before saving it.. "
Exit Sub
err:
Debug.Print "Error No.: " & err.Number & vbNewLine & vbNewLine & "Description: " & err.Description, vbCritical, "Error"
If err.Number = -2147467259 Then
MsgBox "Error Occured - Check if the Files to be embedded or the destination PPT is in the same folder as that of the Excel file..."
End If
If err.Number = 462 Then
Set PP_File = PowerPointApp.Presentations.Add
GoTo rrr
End If
If err.Number = 16 Then
MsgBox "Check if the Excel Files to be embedded is in the same folder.."
End
End If
End Sub
I have a similar issue with Excel and the On Error Resume Next code. Although I use it sparingly (I prefer to experience all the errors and handle them appropriately) it can be useful in some limited situations. I have found ways to rethink some code, in your for example you show this:
On Error Resume Next
'Is PowerPoint already opened?
Set PowerPointApp = GetObject(class:="PowerPoint.Application")
'Clear the error between errors
err.Clear
'If PowerPoint is not already open then open PowerPoint
If PowerPointApp Is Nothing Then Set PowerPointApp = CreateObject(class:="PowerPoint.Application")
I would recode this piece as follows:
bPPOpen = GetObject(class:="PowerPoint.Application")
If bPPOpen Then
Set PowerPointApp = GetObject(class:="PowerPoint.Application")
Else bPPOpen = False Then
Set PowerPointApp = CreateObject(class:="PowerPoint.Application")
Endif
Using this technique you never have to attempt to SET the object unless you know it's available. Further, since you are not using a raised error you don't have to deal with some of the error 'clean up'.

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

Error Code 91 when trying to install on different machine

I've got an issue with some code when I've tried to install some code on a colleagues machine. The machine and version of Outlook are exactly the same and reference the same libraries. However, when I try and run the script on her machine, it throws up an error 91 on the 'Set xlWB = xlApp.Workbooks.Open(strPath)'.
The intention is to export necessary data from a selected email message into an Excel spreadsheet located in a specified directory.
Any clues as to what I should be trying in order to eliminate the error? First half of the code below.
Many thanks!
Option Explicit
Sub ServiceRequestTool()
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
Dim rCount As Long
Dim bXStarted As Boolean
Dim enviro As String
Dim strPath As String
Dim currentExplorer As Explorer
Dim Selection As Selection
Dim olItem As Outlook.MailItem
Dim obj As Object
Dim strColA, strColB, strColC As String
strPath = "H:\My Documents\General Docs\Govtnz-Service-Request.xlsm"
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
If Dir$("H:\My Documents\General Docs\Govtnz-Service-Request.xlsm") = "" Then
MsgBox "Contact the spreadsheet administrator for assistance.", vbOKOnly + vbCritical, "File not found!"
Exit Sub
End If
End If
On Error GoTo 0
Set xlWB = xlApp.Workbooks.Open(strPath)
Set xlSheet = xlWB.Sheets("requestAssignment")
On Error Resume Next
rCount = xlSheet.Range("C" & xlSheet.Rows.Count).End(-4162).Row + 1
Set currentExplorer = Application.ActiveExplorer
Set Selection = currentExplorer.Selection
For Each obj In Selection
Set olItem = obj
strColA = olItem.SenderName
strColB = olItem.SenderEmailAddress
strColC = olItem.ReceivedTime
xlSheet.Range("B" & rCount) = strColC
xlSheet.Range("C" & rCount) = strColA
xlSheet.Range("D" & rCount) = strColB
rCount = rCount + 1
Next
xlWB.Close 1
If bXStarted Then
xlApp.Quit
End If
Set olItem = Nothing
Set obj = Nothing
Set currentExplorer = Nothing
Set xlApp = Nothing
Set xlWB = Nothing
Set xlSheet = Nothing
End Sub
You are most probably getting that error because there is no instance of Excel which is running.
You need to create a new instance when GetObject doesn't find one.
You are checking for the existence of the file if Err <> 0? i.e when no Excel instance is found? That doesn't make sense. Check for the existence of the file first and then check for Excel.
Is this what you are trying? (untested)
Change your code
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
If Dir$("H:\My Documents\General Docs\Govtnz-Service-Request.xlsm") = "" Then
MsgBox "Contact the spreadsheet administrator for assistance.", _
vbOKOnly + vbCritical, "File not found!"
Exit Sub
End If
End If
On Error GoTo 0
to
'~~> Move ths out of that IF/EndIf
If Dir$("H:\My Documents\General Docs\Govtnz-Service-Request.xlsm") = "" Then
MsgBox "Contact the spreadsheet administrator for assistance.", _
vbOKOnly + vbCritical, "File not found!"
Exit Sub
End If
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
Set xlApp = CreateObject("Excel.Application") '<~~ Add this line
End If
On Error GoTo 0
If xlApp Is Nothing Then
MsgBox "Excel is not installed"
Exit Sub
End If

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