I'm having issues with selecting cells when I export queries with the below code. I keep getting an error "Select method of Range class failed" with the Sheet.Cells(2,1).Select portion. I'm able to get this to work when I only have 1 worksheet, but when I have multiple sheets I get the error.
Code:
Function ExcelExport()
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim i As Integer
Dim intColumnCount As Integer
Dim j As Integer
Dim recExcelQuery As Recordset
Dim recSelectedField As Recordset
Dim strCurrentField As String
Dim strExcelCurrentValue As String
Dim strFileLocation As String
Dim strSelectedField As String
Dim recExcel As Recordset
Dim intExcelQuery As Integer
Dim strQueryName As String
On Error GoTo StopIt
DoCmd.SetWarnings False
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Add
Set recExcel = CurrentDb.OpenRecordset("tblExcel") 'Pulls list of queries to export
With recExcel
Do Until .EOF
strSelectedField = ![exc_query]
intExcelQuery = intExcelQuery + 1
strQueryName = ![exc_query]
Set xlSheet = xlBook.Worksheets(intExcelQuery)
Set recExcelQuery = CurrentDb.OpenRecordset(strSelectedField)
Set Sheet = xlApp.ActiveWorkbook.Sheets(intExcelQuery)
Set recSelectedField = CurrentDb.OpenRecordset(strSelectedField)
j = 1
intColumnCount = 0
With recSelectedField
If Not .EOF And Not .BOF Then
recSelectedField.MoveFirst
For i = 0 To recExcelQuery.Fields.Count - 1
intColumnCount = intColumnCount + 1
Sheet.Cells(j, intColumnCount).Value = recSelectedField.Fields(i).Name
Sheet.Cells(j, intColumnCount).Font.Bold = True
Sheet.Cells(j, intColumnCount).HorizontalAlignment = xlCenter
Sheet.Cells(j, intColumnCount).Interior.ColorIndex = 48
Sheet.Cells(j, intColumnCount).Borders.LineStyle = xlContinuous
Sheet.Cells(j, intColumnCount).Borders.Weight = xlThin
Next i 'Query field name
End If
End With
j = 2
recExcelQuery.MoveFirst
With recExcelQuery
Do Until .EOF
intColumnCount = 0
For i = 0 To recExcelQuery.Fields.Count - 1
strExcelCurrentValue = recExcelQuery.Fields(i).Name
intColumnCount = intColumnCount + 1
strCurrentField = IIf(IsNull(recExcelQuery(i)), "", recExcelQuery(i))
Sheet.Cells(j, intColumnCount).Value = strCurrentField
Sheet.Cells(j, intColumnCount).HorizontalAlignment = xlRight
Next i 'Query Field Name
StepOut:
j = j + 1
.MoveNext
Loop
End With
Sheet.Name = strQueryName
Sheet.Cells.EntireColumn.AutoFit
Sheet.Cells(2,1).Select
xlApp.ActiveWindow.FreezePanes = True
recExcel.MoveNext
Loop
End With
xlApp.DisplayAlerts = False
strFileLocation = "C:\Spreadsheet"
xlApp.ActiveWorkbook.SaveAs strFileLocation
xlApp.DisplayAlerts = True
xlApp.Quit
DoCmd.SetWarnings True
Exit Function
StopIt:
MsgBox Err.Description
Resume
End Function