簡體   English   中英

訪問VBA與Excel進行交互,第二次出現錯誤91

[英]Access VBA interacting with Excel, second time get Error 91

第二次運行時,此腳本出現問題。 第一次運行腳本沒有問題,如果我關閉訪問權限並重新運行腳本,我也沒有問題,但是在說10分鍾內運行時,出現錯誤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

請閱讀以下博客: https : //msdn.microsoft.com/zh-cn/library/aa264506(v=vs.60).aspx

祝好運!

不要將一個With Selection ... End With嵌套在一起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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM