在vba中使用for子名称

时间:2016-09-12 16:34:44

标签: excel-vba vba excel

private sub sub1()
sub1.value=true
end sub    

private sub sub2()
sub2.value=true
end sub

private sub sub3()
sub3.value=true
end sub

我怎么能以真实的方式编写以下代码?

dim x as integer    
for x = 1 to 3

private sub subx()
subx.value=true
end sub

1 个答案:

答案 0 :(得分:0)

你不能。

最好定义Class Module,然后创建该类的对象数组。例如,如果您有一个名为Automobile的类:

Option Explicit

Private mySpeed As Double

Public Property Let Speed(ByVal newSpeed)
    mySpeed = newSpeed
End Property

Public Property Get Speed() As Double
    Speed = mySpeed
End Property

Private Sub class_initialize()
    mySpeed = 0#
End Sub

然后在常规Module中,您可以定义:

Option Explicit

Sub test()
    Dim autos(1 To 5) As Automobile
    Dim i As Integer
    For i = 1 To 5
        Set autos(i) = New Automobile
        autos(i).Speed = i * 15#
    Next i
End Sub