这是我的第一个VBA项目,也是我的第一篇文章。所以请原谅我,如果... 它尝试了我在网络上可以找到的所有内容,我想了几天,最后放弃了。 我以理解Web建议的方式做了几个类的实现。不幸的是,这个(但其他)不起作用。如果我放弃使用PRIVATE的数据封装,则可以使用,但似乎不是干净的编程。 我复制了下面代码的基本部分。这应该足以重现错误(91)。 我希望有人知道一些魔术人物。我想那不多。
预先感谢, 骑警
PC:Win7Enterprise-64 SP1,Excel 365 ProPlus-32(1808)
Class Module
Option Explicit
Private resWrkBook As Workbook 'resultXLS - Result workbook
‘Properties
Public Property Let resultXLS(ByVal resultXLS As Workbook) 'Write value to class variable
Set resWrkBook = resultXLS 'Assign value to property
End Property
Public Property Get resultXLS() As Workbook 'Read value from class variable
Set resultXLS = resWrkBook 'Return value from property
End Property
编程模块
Option Explicit
Public Sub main()
Dim wbs As XlsClass_Module 'declaration
‘Short (version S)
Set wbs.resultXLS = Workbooks.Add '=> Error 91
‘Long (version L, alternative)
Dim wrk As Workbook
Set wbs = New XlsClass_Module 'instance of Workbook Class
Set wrk = Workbooks.Add
Set wbs.resultXLS = wrk '=> Error 91
End Sub
答案 0 :(得分:0)
这是起作用的类模块和起作用的主要代码。请查看以下代码:
Option Explicit
Private resWrkBook As Workbook 'resultXLS - Result workbook
'Properties
Public Property Set resultXLS(ByVal resultXLS As Workbook) 'Write value to class variable
Set resWrkBook = resultXLS 'Assign value to property
End Property
Public Property Get resultXLS() As Workbook 'Read value from class variable
Set resultXLS = resWrkBook 'Return value from property
End Property
现在,需要更改的调用代码(注意NEW关键字):
Public Sub main()
Dim wbs As XlsClass_Module 'declaration
Set wbs = New XlsClass_Module
'Short (version S)
Set wbs.resultXLS = Workbooks.Add '=> Error 91
'Long (version L, alternative)
Dim wrk As Workbook
Set wbs = New XlsClass_Module 'instance of Workbook Class
Set wrk = Workbooks.Add
Set wbs.resultXLS = wrk '=> Error 91
End Sub
此外,对于使用SET的变量,您需要将其设置为空,以释放内存:
EX:set wbs = Nothing