在vba中循环遍历类的属性

时间:2013-08-22 16:11:40

标签: excel vba excel-vba

我创建了这个类,

Interval.cls
public x as new collection
public y as new collection
public z as string

我希望遍历属性,因为我希望用户在表格中选择输入x,y,z

sub test()

dim inter as new Intervals

inter.x.add "a"
inter.x.add "a"
inter.x.add "b"
inter.x.add "b"
inter.x.add "b"

userString1 = x
userString2 = a

'我想让它变得动态,以便无论用户想要什么,我都可以提供结果。 '我只是想让userString与我的属性进行比较

for each i in inter

'所以我希望我在这个循环中成为我的属性x,y,z所以我可以制作if语句     if(i = userString1)然后

end if
next i
end sub

我知道我可以在课堂上做一个微调,让它可以迭代,我不知道怎么做

感谢任何帮助

2 个答案:

答案 0 :(得分:2)

'in class
Public Property Get Item(i As Integer) As Variant

   Select Case ndx
      Case 1: Item = Me.x
      Case 2: Item = Me.y
      Case 3: Item = Me.z
   End Select

End Property

'in sub
Dim c as Collection
Dim s as String

For i = 1 to 3
   if i < 3 then 
      set c = inter.Item(i)
      'iterate through collection
   else
      s = inter.Item(i)
   end if
next i
像这样的东西可能是最简单的方法,我没有测试它,但希望它至少让你开始

答案 1 :(得分:0)

这是你追求的那种东西吗?

'in class
Public x As New Collection
Public y As New Collection
Public z As String
Public Property Get Item(i As Integer) As Variant

   Select Case i
      Case 1: Item = Me.x
      Case 2: Item = Me.y
      Case 3: Item = Me.z
   End Select

End Property

Sub try()

Dim userString2 As String
Dim userString1 As String
Dim inter As Interval
Dim i As Integer

Set inter = New Interval

inter.x.Add "a"
inter.x.Add "a"
inter.x.Add "b"
inter.x.Add "b"
inter.x.Add "b"

userString2 = "aabbb"

For i = 1 To inter.x.Count

       userString1 = userString1 & inter.x.Item(i)
Next i

 If userString1 = userString2 Then
 '<do whatever>
 End If
End Sub

好的,忘记课程并使用数组怎么样?字符串数组可以是任意长度,您可以通过调用过程动态控制它的大小。

Sub tryWithArray(ByRef StringArray() As String)

Dim userString2 As String
Dim i As Integer

userString2 = "b"


For i = 1 To UBound(StringArray())
    If userString2 = StringArray(i) Then
        'do something
    End If
Next i

End Sub