访问VBA与Excel交互,第二次获得错误91

我在第二次运行时遇到了这个脚本的问题。 我第一次运行脚本没有问题,如果我closures访问并重新运行脚本,我也没有问题,但在10分钟内运行时,我得到错误91“对象variables或块variables未设置”

脚本似乎卡在第二次运行格式化电子表格的行上。 ( With Selection .Font.Bold = True

脚本是:

 Option Compare Database Option Explicit Public Function LookInduct() On Error GoTo Induct_err Dim ExcelApp As New excel.Application Dim WorkBook As excel.WorkBook Dim Linecount As Integer Dim SaveDetails As String SaveDetails = "C:\LookToInductReport.xlsx" If Len(Dir(SaveDetails)) > 0 Then Kill SaveDetails End If DoCmd.TransferSpreadsheet acExport, 10, "LookToInductReport_04", SaveDetails, True, "LookToInduct" Set ExcelApp = CreateObject("excel.application") ExcelApp.Visible = False '------------------------------------------------------------ ' Format the Excel File '------------------------------------------------------------ Linecount = DCount("[NSN]", "LookToInductReport_04") + 1 Set WorkBook = ExcelApp.Workbooks.Open(SaveDetails, , False) WorkBook.Sheets("LookToInduct").Select With Selection ExcelApp.Range("A1:M1").Select With Selection .Font.Bold = True '<- error #91 here .WrapText = True .Interior.Pattern = xlSolid .Interior.Color = 16764057 .VerticalAlignment = xlTop End With End With WorkBook.Save WorkBook.Close ExcelApp.Close ExcelApp.Quit Set WorkBook = Nothing Set ExcelApp = Nothing MsgBox "Report saved" Exit Function Induct_err: WorkBook.Save WorkBook.Close ExcelApp.Quit MsgBox Err.Number & vbCr & Err.Description Exit Function End Function 

不要嵌套一个With Selection ... End With另一个With Selection ... End With

Selection是Excel应用程序对象的一个​​属性,因此使用With ExcelApp.Selection而不是仅With Selection

 'With Selection ExcelApp.Range("A1:M1").Select 'With Selection With ExcelApp.Selection .Font.Bold = True .WrapText = True .Interior.Pattern = xlSolid .Interior.Color = 16764057 .VerticalAlignment = xlTop End With 'End With 

请阅读以下博客: https : //msdn.microsoft.com/en-us/library/aa264506(v=vs.60).aspx

祝你好运!