簡體   English   中英

Excel VBA對象變量未設置錯誤91

[英]Excel VBA Object Variable Not Set Error 91

今天,我在使用特定的VBA代碼行時遇到了麻煩。 我不斷收到有關“未設置對象變量...”的錯誤消息,這是VBA錯誤91。

以下代碼是發生錯誤的位置,位於mFactory的modules文件夾中

Public Function CreateInterface(InterfaceWB As Workbook, SourceFilepath As String, SourceBookPass As String) As CInterface
     Dim NewInterface As CInterface
     Set NewInterface = New CInterface

     NewInterface.InitiateProperties InterfaceWB:=InterfaceWB, SourceFilepath:=SourceFilepath, SourceBookPass:=SourceBookPass <------Error Here
     Set CreateInterface = NewInterface
End Function

在從ThisWorkbook打開的工作簿上調用此方法:

Public Interface As CInterface

Private Sub Workbook_Open()
     Dim InterfaceWB As Workbook
     Dim SourceFilepath As String
     Dim SourceBookPass As String

     Set InterfaceWB = ThisWorkbook
     'Change this variable if the location of the source workbook is changed
     SourceFilepath = "C:\file.xlsx"
     'Change this variable if the workbook password is changed
     SourceBookPass = "password"

     Set Interface = mFactory.CreateInterface(InterfaceWB, SourceFilepath, SourceBookPass)
End Sub

在類模塊CInterface中實現了mFactory模塊中調用的InitiateProperties方法:

Sub InitiateProperties(InterfaceWB As Workbook, SourceFilepath As String, SourceBookPass As String)
     pInterfaceWB = InterfaceWB
     pSourceFilepath = SourceFilepath
     pSourceBookPass = SourceBookPass
End Sub

我的VBAProject結構如下:

VBAProject
     Microsoft Excel Objects
          Sheet1
          ThisWorkbook
     Modules
          mFactory
     Class Modules
          CInterface

我所做的一件事是將CInterface實例化更改為PublicNotCreatable,因為在將私有參數傳遞給公共函數時遇到錯誤。 我正在嘗試使用“構造函數”來創建CInterface類的一個實例,以在VBA項目中全局使用。 為什么在出現錯誤的行中未設置對象?

當您嘗試使用或分配對象變量而不進行設置時(在這種情況下為pInterfaceWB),將發生此錯誤。

Sub InitiateProperties(InterfaceWB As Workbook, SourceFilepath As String, SourceBookPass As String)
     pInterfaceWB = InterfaceWB

應該

Set pInterfaceWB = InterfaceWB

暫無
暫無

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

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