今天我一直在遇到特定的VBA代碼行。我不斷收到關於「對象變量未設置......」這是VBA錯誤的錯誤消息91Excel VBA對象變量未設置錯誤91
下面的代碼是發生錯誤,位於模塊文件夾mFactory
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項目中全局使用。爲什麼對象沒有設置在行我得到錯誤?
'mFactory'是不是對象。已經嘗試過'Set Interface = CreateInterface(InterfaceWB,SourceFilepath,SourceBookPass)'? – PatricK
'mFactory'是同一個VBAProject中的一個模塊。在這裏,我正在調用模塊的方法。對不起,如果我的行話是不正確的VBA,我不是很熟悉這種語言。 –