循环通过类属性?

时间:2015-07-02 18:07:43

标签: vba excel-vba excel

我有一个班级("姓名"):

Option Explicit

Public companyName As String
Public companyCode As String
Public companyCountry As String
Property Get fullInfo() As String
    fullInfo = "Code " & companyCode & " is " & companyCountry & " for " & companyName
End Property

并且在模块的Sub()中,我有以下内容:

Sub classTest()

Dim c1 As New Names
Dim c2 As New Names
c1.companyCode = 14
c1.companyCountry = "Ivory Coast"
c1.companyName = "Ivory Company"
c2.companyCode = 11
c2.companyCountry = "Cameroon"
c2.companyName = "Cameroon Company"

Dim i As Integer

debug.print c1.fullInfo

End Sub

这将正确打印" Code 14为Ivory Coast for Ivory Company"。

如何编写循环来浏览所有属性(正确的单词是c1,c2,a'属性'?)。我尝试了类似下面的内容,但它没有工作:

for i = 1 to 2
 debug.print ci.fullInfo
next i

你可以看到它显然不会起作用 - 但我怎么能这样做呢?对不起,我不知道c1部分被叫什么,也不知道之后的部分是什么。被称为)

2 个答案:

答案 0 :(得分:2)

如果将c1,c2等存储在数组或集合中,则可以使用标准For循环遍历它们,并为每个循环调用fullInfo。

Sub Tester()

    Dim col As New Collection, n As Names, i

    For i = 1 To 10
        Set n = New Names
        n.companyCode = i
        n.companyCountry = "Country_" & i
        n.companyName = "Company_" & i
        col.Add n
    Next i


    For Each n In col
        Debug.Print n.fullInfo
    Next n

End Sub

答案 1 :(得分:1)

查看每个循环的。像

这样的东西
DEBUG