I've got this really frustrating problem. The code below is supposed to export a query from Access to Excel and then color the first row, bold it, and autofit the whole worksheet.
This needs to happen multiple times, so I've simply copy pasted the number of times needed with the little changes to the dim names. Unfortunately, it stops working after the second round and gives me the error "Object variable or With block variable not set" and then it highlights a section of the code as seen below. I mean, at this point, I'm just going to do this manually, so it's not a life threatening issue, but I'd love to figure out how to make this work.
Thanks, here's the code that's duplicated multiple times:
Private Sub cmdFinal_Click()
Dim fileLocation As String ' Main folder
Dim finalExport As String
fileLocation = "C:\MYDOCS\Latest\"
finalExport = "FINAL_EXPORT_" & UCase(Format(DateAdd("m", -7, Date), "MMMyy")) & "-" & UCase(Format(DateAdd("m", -2, Date), "MMMyy"))
' Export queries to Final Excel file
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "qryFINAL", fileLocation & finalExport True, finalExport
DoEvents
Me.ProgressBar.Visible = True
Me.ProgressBar.Width = 500
Me.Repaint
DoEvents
' Open Excel file, apply colors, save, and quit
Set xl = CreateObject("Excel.Application")
Set wr = xl.Workbooks.Open(fileLocation & finalExport & ".XLSX")
Call ColorMe
DoEvents
wr.Save
wr.Close
xl.Quit
DoEvents
Set sh = Nothing
Set wr = Nothing
Set xl = Nothing
DoEvents
Sub ColorMe()
'
' Format document and make it pretty
'
Set sh = wr.Worksheets(1)
With sh
sh.Rows("1:1").EntireRow.Select
With Selection.Interior <----------Here's where the error occurs
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorDark1
.TintAndShade = -0.499984740745262
.PatternTintAndShade = 0
End With
With Selection.Font
.ThemeColor = xlThemeColorDark1
.TintAndShade = 0
End With
End With
Selection.Font.Bold = True
Cells.Select
Cells.EntireColumn.AutoFit
DoEvents
End Sub