excel - VBA Class() 对象作为另一个类的属性

标签 excel class vba

我正在尝试创建一个类来保存可变数量的项目(它们本身就是另一个类对象)。

所以,我有第 2 课:

' Class 2 contain each individual quote elements (OTC and MRC)

Private pOTC As String
Private pMRC As String
Public Property Get OTC() As String
    OTC = pOTC
End Property
Public Property Let OTC(Value As String)
    pOTC = Value
End Property

Public Property Get MRC() As String
    MRC = pMRC
End Property
Public Property Let MRC(Value As String)
    pMRC = Value
End Property

然后类 1 包含类 2 的数组:

Private pCurr As String
Private pQuote(20) As Class2

Public Property Get Curr() As String
    Curr = pCurr
End Property
Public Property Let Curr(Value As String)
    pCurr = Value
End Property

Public Property Set Quote(Index As Integer, cQuote As Class2)
    Set pQuote(Index) = cQuote
End Property

Public Property Get Quote(Index As Integer) As Class2
    Quote = pQuote(Index)
End Property

我想做的是:

Dim myQuotes As Class1
Set myQuotes = New Class1

myQuotes.Curr = "GBP"
myQuotes.Quote(3).OTC = "1200"  

第一行设置 myQuotes.Curr 没有问题,但是当我尝试在数组内设置值时,下一行出现错误,运行时 91 对象变量或未设置 block 变量

有任何关于我做错了什么以及如何设置类数组中元素的值的指示吗?

提前致谢!

最佳答案

当您myQuotes.Quote(3)时,您调用Property Get Quote时出现问题。

您的 Class2 内部数组未实例化,因此 pQuote(Index) 引用 Nothing 的数组元素,当您myQuotes.Quote(3).OTC = 您尝试分配给 Nothing 但失败了。

您需要确保pQuote(Index)已实例化;您可以根据需要执行此操作:

Public Property Get Quote(Index As Integer) As Class2
   If (pQuote(Index) Is Nothing) Then Set pQuote(Index) = New Class2
   Set Quote = pQuote(Index)
End Property

(注意所需的设置)

或者通过向Class1添加初始化例程:

Private Sub Class_Initialize()
    Dim Index As Long
    For Index = 0 To UBound(pQuote)
         Set pQuote(Index) = New Class2
    Next
End Sub

关于excel - VBA Class() 对象作为另一个类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17486215/

相关文章:

python - Xlsxwriter writer 正在编写自己的工作表并删除现有工作表

excel - 排序而不改变单元格索引

c++ - 在lua中覆盖c++方法并在c++中调用它

C++ fstream 如何从文本文件中读取特定行

vba - 为什么在 VBA 错误时必须从 Windows 任务管理器终止 Excel session

html - 通过 VBA 使用 QuerySelector 单击 HTML 元素

vba - 如何在 VBA 中实现 "do not show this message again"复选框?

excel - font.TintAndShade 无法更改文本的亮度

c++ - 声明在类中定义的结构

excel - 如何在 VBA 中将字符串作为命令运行