UBound数组定义

时间:2018-04-27 14:31:20

标签: vba

无法理解如何使用UBound。

如果我有一个动态列A,其中行计数不断变化,但我想抓住上限以在for循环中定义 - 我将如何这样做?我通过以下方法不断收到运行时错误。

arr = Worksheets("Sheet1").Range("A1").CurrentRegion.Value
For i = 1 to UBound(arr, 1)

etc. 

Next i

1 个答案:

答案 0 :(得分:1)

当设置一个等于范围值的数组时,它会自动将其设置为二维数组,即使该范围只有一列。请看下面的例子:

 Private Sub workingWithArrayBounds()

    Dim Arr As Variant
    Dim RowIndex As Long
    Dim ColumnIndex As Long

    Arr = Worksheets("Sheet1").Range("A1").CurrentRegion.Value

    'VBA FUNCTION FOR CHECKING IF SOMETHING IS AN ARRAY
    If IsArray(Arr) Then

        'FIRST LOOP GOES THROUGH THE ROWS
        For RowIndex = LBound(Arr, 1) To UBound(Arr, 1)

            'THE SECOND LOOP GOES THROUGH THE COLUMNS
            For ColumnIndex = LBound(Arr, 2) To UBound(Arr, 2)

                'NOW YOU HAVE ACCESS TO EACH ELEMENT USING THE ROWINDEX AND THE COLUMN INDEX
                Debug.Print Arr(RowIndex, ColumnIndex)

            Next

        Next

    End If

End Sub

如果只有一列数据,则边界看起来像(1到x,1到1)。所以你需要传递第二个边界。为了安全起见,始终建议在循环数组时同时使用LBoundUBound,因为这些数组可能因数组而异。

要检查的另一件事是数组是否实际分配。在将数组设置为等于范围值的方案中,您可以首先检查您的范围中是否确实存在要检索的值。

另一种方法是使用函数检查并查看数组是否为空。 Cpearson具有良好的功能以及许多其他有用的功能@ http://www.cpearson.com/excel/vbaarrays.htm

Public Function IsArrayEmpty(Arr As Variant) As Boolean
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' IsArrayEmpty
' This function tests whether the array is empty (unallocated). Returns TRUE or FALSE.
'
' The VBA IsArray function indicates whether a variable is an array, but it does not
' distinguish between allocated and unallocated arrays. It will return TRUE for both
' allocated and unallocated arrays. This function tests whether the array has actually
' been allocated.
'
' This function is really the reverse of IsArrayAllocated.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Dim LB As Long
Dim UB As Long

Err.Clear
On Error Resume Next
If IsArray(Arr) = False Then
    ' we weren't passed an array, return True
    IsArrayEmpty = True
End If

' Attempt to get the UBound of the array. If the array is
' unallocated, an error will occur.
UB = UBound(Arr, 1)
If (Err.Number <> 0) Then
    IsArrayEmpty = True
Else
    ''''''''''''''''''''''''''''''''''''''''''
    ' On rare occassion, under circumstances I
    ' cannot reliably replictate, Err.Number
    ' will be 0 for an unallocated, empty array.
    ' On these occassions, LBound is 0 and
    ' UBoung is -1.
    ' To accomodate the weird behavior, test to
    ' see if LB > UB. If so, the array is not
    ' allocated.
    ''''''''''''''''''''''''''''''''''''''''''
    Err.Clear
    LB = LBound(Arr)
    If LB > UB Then
        IsArrayEmpty = True
    Else
        IsArrayEmpty = False
    End If
End If

End Function