在类中使用数组(Excel VBA)

时间:2013-06-11 15:16:06

标签: arrays excel class vba

我正在研究执行以下操作的程序的一部分:

1)确定某个单元格中是否存在“X”以及标题是否与用户输入匹配

2)如果这是真的,则将标题的内容添加到类中的元素

例如,如果行的“离合器”标题下有“X”,则在此情况下将“离合器”添加到pos.clutch。

以下是完成此操作的内容(编辑:这是在Do While循环中,因此R + 1,对不起,如果最初没有澄清):

If sh.Cells(R + 1, Clutch) = "X" And _
   sh.Cells(1, Clutch).Value = CStr(cboPart.Value) Then
     pos.Clutch = sh.Cells(1, Clutch)

现在,问题是我为每个元素都有一长串的ElseIf语句(总共有6个。)我想将它转换为For循环,经过一些研究后,我想出了一个我将包含的数组在类模块中将是最好的方式,因为我可以循环遍历数组中的每个值。

我想知道如何在类模块中创建由类元素组成的数组,以及是否可以在For循环中为每个类元素设置值。此外,如果有更好的解决方案,我想了解更多。

1 个答案:

答案 0 :(得分:1)

我不是100%肯定你的意思。但基于帖子的第一部分,这里有一些带注释的示例代码

Option Explicit

Sub tryme()

    Dim inp As String
    inp = InputBox("Whats the header:")
    Dim ws As Worksheet
    Set ws = Sheets("Sheet1")
    Dim rng As Range
    Dim i As Long, j As Long

    For i = 1 To ws.Cells(1, Columns.Count).End(xlToLeft).Column
        If StrComp(inp, CStr(ws.Cells(1, i).Value), 1) = 0 Then
            For j = 2 To ws.Cells(Rows.Count, i).End(xlUp).Row
                Set rng = ws.Cells(j, i)
                    If StrComp(CStr(rng.Text), "X", 1) = 0 Then
                        ' youve just found a match
                        ' so if your class constructor takes some params
                        ' for example
                        ' ...MyClass(header as String, row as Long)
                        ' then you can call it
                        ' ...dim newMyClassObj(Cstr(ws.Cells(1, i).Text), rng.row)
                    End If
                Set rng = Nothing
            Next j
        End If
    Next i

End Sub