检查 VBA 中的数组

Check For Array In VBA

我有一个列表 - 我刚刚找到了允许从我的列表中进行多项选择的语法:

Dim Oldvalue As String
Dim Newvalue As String

On Error GoTo Exitsub
If Target.Address = "$B" Then
  If Target.SpecialCells(xlCellTypeAllValidation) Is Nothing Then
    GoTo Exitsub
  Else: If Target.Value = "" Then GoTo Exitsub Else
    Application.EnableEvents = False
    Newvalue = Target.Value
    Application.Undo
    Oldvalue = Target.Value
    If Oldvalue = "" Then
      Target.Value = Newvalue
    Else
      Target.Value = Oldvalue & ", " & Newvalue
    End If
  End If
End If
Application.EnableEvents = True

Exitsub:
Application.EnableEvents = True

我知道所选值列表将存储在变量中 Target.Value - 但我如何:

1) Check the length of Target.Value (so I know if I have 1 selected or multi?)

2) Iterate each selection?

您需要将 Target.Value 分配给 Variant 变量。请记住在变量名后加上括号,以表示您正在分配一个数组。

然后您可以使用 LBoundUBound 找到数组的维度,您也可以遍历数组。很确定这就是您想要做的。

Sub get_vals()

    Dim arr() As Variant
    Dim i As Long

    arr = Range("A1:A5").Value

    Debug.Print UBound(arr, 1) ' Print rows
    Debug.Print UBound(arr, 2) ' Print columns

    For i = LBound(arr, 1) To UBound(arr, 1) ' Iterate through the rows of the array

        Debug.Print arr(i, 1)

    Next i

End Sub

编辑

如前所述,您将无法将一个单元格范围分配给 Array Variant。您可能希望只使用 Dim arr As Variant。这将允许您将单个单元格范围分配给变量。然后您可以检查类型以确定是否需要迭代数组或只使用单个 string/integer.

If TypeName(arr) = "Variant()" Then
    ' Iterate
Else
    ' Work with single string/integer
End If

无需分配数组,您可以使用

Target.Rows.Count    'number of rows
Target.Columns.Count 'number of columns
Target.Cells.Count   'number of cells

您可以使用索引或

遍历它们
Dim cl As Range
For Each cl In Target.Cells 'For Each loops are much faster then looping using indices
    'do something with cl
Next cl

另请注意 Thomas Inzina 的评论,即即使您的范围不连续,您也可以通过这种方式获得所有单元格。

编辑: For Each 循环比使用索引遍历单元格更快,即

For i = 1 To Target.Rows.Count
    For j = 1 To Target.Columns.Count
        'do something with Target.Cells(i, j)
    Next j
Next i

按照 luke_t 建议使用数组可能会更快。