通过'属性传递类对象得到'在父类中不会影响嵌套的类对象

时间:2016-08-08 20:06:41

标签: excel-vba vba excel

我有这种类的层次结构,定义如下

cQuestion:

Private pText As String

Private Sub Class_Initialize()
pText = ""
End Sub

Property Let Text(T As String)
    pText = T
End Property

Property Get Text() As String
    Text = pText
End Property

cQuestionList:

Private pQList() As New cQuestion
Private pListLen As Integer

Private Sub Class_Initialize()
    pListLen = 0
End Sub

Public Sub AddEnd(Q As String)
    pListLen = pListLen + 1
    ReDim Preserve pQList(1 To pListLen)
    pQList(pListLen).Text = Q
End Sub

Public Function Format() As String
    Dim i As Integer
    If pListLen = 0 Then
        FormatList = "There are no questions in this category" + vbNewLine
    Else
        FormatList = "Questions:" + vbNewLine
        For i = 1 To pListLen
            FormatList = FormatList + "• " + pQList(i).Text + vbNewLine
        Next i
    End If
End Function

cCategory:

Private pName As String
Private pQList As New cQuestionList

Private Sub Class_Initialize()
    pName = ""
End Sub

Property Get QuestionList() As cQuestionList
    Set QuestionList = pQList
End Property

Property Let Name(N As String)
    pName = N
End Property

Property Get Name() As String
    Name = pName
End Property

当我尝试拨打Category.QuestionList.AddEnd "Question Here"时, 它不会抛出任何错误。但是,当我随后致电MsgBox Category.QuestionList.Format时,我会收到一个空白消息框。我不确定这最终是如何空白,因为格式应始终返回文本。我在这里做错了什么?我已经查看了通过let传递类对象并在父类中获取的其他示例,并且无法看到我正在做什么是不同的。有什么建议吗?

示例代码:

Dim C as New cCategory
C.QuestionList.AddEnd "A Question"
C.QuestionList.AddEnd "Another Question"
MsgBox C.QuestionList.Format

1 个答案:

答案 0 :(得分:2)

Option Explicit放在每个模块的顶部,您将立即看到问题:

Public Function Format() As String
    Dim i As Integer
    If pListLen = 0 Then
        FormatList = "There are no questions in this category" + vbNewLine
           '^^^^ Variable not defined.
    Else
        FormatList = "Questions:" + vbNewLine
        For i = 1 To pListLen
            FormatList = FormatList + "• " + pQList(i).Text + vbNewLine
        Next i
    End If
End Function

您需要将Public Function Format() As String更改为Public Function FormatList() As String或将FormatList分配更改为Format

我个人会使用FormatList命名来避免与Format功能发生冲突。