我在第二次運行時遇到了此腳本的問題。 第一次運行腳本我沒有問題,如果我關閉訪問並重新運行腳本,我也沒有問題,但在10分鐘內運行時,出現錯誤91「對象變量或塊變量未設置」訪問VBA與Excel交互,第二次獲取錯誤91
腳本似乎卡在第二次運行時格式化電子表格的行上。 (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
請閱讀:[MCVE]。然後使用重現問題的最小代碼編輯您的問題,並標記引發錯誤的行。謝謝。 – Andre
另外,請閱讀http://stackoverflow.com/help/merging-accounts - 您似乎正在使用兩個帳戶。 – Andre
已將代碼挑選出來,以顯示格式化電子表格的第二次運行時發生問題的唯一區域。 – RyanE