Excel 通过'传递类对象;属性获取';在父类中,不影响嵌套的类对象
我有如下定义的类的层次结构 问题:Excel 通过'传递类对象;属性获取';在父类中,不影响嵌套的类对象,excel,vba,Excel,Vba,我有如下定义的类的层次结构 问题: 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 问题列表: Private pQList() As New cQuest
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
问题列表:
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
C类别:
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和get传递类对象的其他示例,但看不出我所做的有什么不同。有什么建议吗
示例代码:
Dim C as New cCategory
C.QuestionList.AddEnd "A Question"
C.QuestionList.AddEnd "Another Question"
MsgBox C.QuestionList.Format
将选项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()作为字符串
更改为Public Function FormatList()作为字符串
,或者将FormatList
赋值更改为格式
我个人会使用格式列表
命名,以避免与格式
函数发生冲突。将选项显式
放在每个模块的顶部,您会立即看到问题:
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()作为字符串
更改为Public Function FormatList()作为字符串
,或者将FormatList
赋值更改为格式
我个人会使用FormatList
命名,以避免与Format
函数发生冲突