对于Excel VBA中的每个类属性

Al.*_*Sal 5 excel vba for-loop class

我有一些看起来像这样的代码:

pos.Clutch = sh2.Cells(R, Clutch)
pos.Wiper = sh2.Cells(R, Wiper)
pos.Alternator = sh2.Cells(R, Alternator)
pos.Compressor = sh2.Cells(R, Compressor)
...
pos.Telephone = sh2.Cells(R, Telephone)
poss.Add pos
Run Code Online (Sandbox Code Playgroud)

poss是一个集合,Clutch,Wiper等是列索引(从1开始).这目前有效,但非常难看.我正在寻找一种方法来做这样的事......

Do While i <= classProperty.count
    For each classProperty in pos
        classProperty = sh2.Cells(R + 1, i)
    Next classProperty
Loop
Run Code Online (Sandbox Code Playgroud)

显然这不起作用,但是有没有人对如何在类中完成大致相同的方法或集合有任何建议?

Dic*_*ika 4

我不知道有什么好的办法。它丑陋的唯一原因是你还没有将它隐藏在类中。采取这个程序

Sub Main()

    Dim clsPos As CPos
    Dim clsPoses As CPoses

    Set clsPoses = New CPoses
    Set clsPos = New CPos

    clsPos.AddFromRange Sheet1.Range("A10:E10")
    clsPoses.Add clsPos

End Sub
Run Code Online (Sandbox Code Playgroud)

这没什么难看的。现在AddFromRange方法有点丑陋,但是你只需要在编写它或数据更改时查看它即可。

Public Sub AddFromRange(ByRef rRng As Range)

    Dim vaValues As Variant

    vaValues = rRng.Rows(1).Value

    Me.Clutch = vaValues(1, 1)
    Me.Wiper = vaValues(1, 2)
    Me.Alternator = vaValues(1, 3)
    Me.Compressor = vaValues(1, 4)
    Me.Telephone = vaValues(1, 5)

End Sub
Run Code Online (Sandbox Code Playgroud)

更新:吃数组而不是范围的替代方法。

Public Sub AddFromArray(vaValues as Variant)

    Me.Clutch = vaValues(1, 1)
    Me.Wiper = vaValues(1, 2)
    Me.Alternator = vaValues(1, 3)
    Me.Compressor = vaValues(1, 4)
    Me.Telephone = vaValues(1, 5)

End Sub
Run Code Online (Sandbox Code Playgroud)