我今天遇到了一系列特定的VBA代码问题。我不断收到有关"对象变量未设置的错误消息..."这是VBA错误91。
以下代码是发生错误的位置,位于modules文件夹中,名称为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
mFactory模块中调用的InitiateProperties方法在类模块CInterface中实现:
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,因为我收到有关将私有参数传递给公共函数的错误。我试图使用&#34;构造函数&#34;创建CInterface类的一个实例以在VBA项目中全局使用。为什么对象没有设置在我遇到错误的行?
答案 0 :(得分:1)
当您尝试使用或分配对象变量而未设置它时会发生错误,在本例中为pInterfaceWB。
Sub InitiateProperties(InterfaceWB As Workbook, SourceFilepath As String, SourceBookPass As String)
pInterfaceWB = InterfaceWB
应该是
Set pInterfaceWB = InterfaceWB