对象variables或在初始工作后没有设置块variables

我有这个非常令人沮丧的问题。 下面的代码应该是从Access导出一个查询到Excel,然后为第一行着色,粗体,并自动整个工作表。

这需要多次发生,所以我只是简单地复制粘贴所需的次数与对昏暗名称的小改动。 不幸的是,它在第​​二轮后停止工作,并给我错误“对象variables或块variables未设置”,然后突出显示了一段代码,如下所示。 我的意思是,在这一点上,我只是手动做这个,所以这不是一个威胁生命的问题,但我很想弄清楚如何做这个工作。

谢谢,这是多次重复的代码:

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 

有几件事情:

1)我看不到方法cmdFinal_Click()被closures – 没有

 End Sub 

线。

2)您应该将variableswr作为parameter passing给ColorMe方法。 否则,此方法不知道要处理的工作簿:

 Sub ColorMe(wr As Excel.Workbook) 

 Call ColorMe(wr) 

3)你不需要select一个范围来格式化。 试试下面的代码:

 Sub ColorMe(wr As Excel.Workbook) Dim sh As Worksheet Dim rng As Excel.Range Set sh = wr.Worksheets(1) Set rng = sh.Rows(1) '<---- you create reference to the first row here ' and later you should use this variable ' instead of selecting cells in Worksheet and ' use Selection. With rng.Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .ThemeColor = xlThemeColorDark1 .TintAndShade = -0.499984740745262 .PatternTintAndShade = 0 End With With rng.Font .ThemeColor = xlThemeColorDark1 .TintAndShade = 0 .Bold = True End With 'Cells.Select '<---- Commented. Can cause errors if worksheet is not active. Cells.EntireColumn.AutoFit DoEvents End Sub