对数组使用UBound

时间:2019-02-14 03:06:43

标签: arrays excel vba

我的代码中有一个声明为Variant的变量

Dim All_WorkWeeks_Entered As Variant

我正在分配如下值

With Worksheets("workweeks")
    All_WorkWeeks_Entered = Application.Transpose(.Range(.Range("A1"), .Cells(.Rows.Count, "A").End(xlUp)))
End With

如果我的“ A”列中只有一个元素,那么我的All_WorkWeeks_Entered将是一个字符串。

以及我正在使用的另一部分代码

For Counter = 1 To UBound(All_WorkWeeks_Entered)

Next Counter

UBound不能用于字符串。我将如何始终将All_WorkWeeks_Entered作为数组?

3 个答案:

答案 0 :(得分:0)

如果转置,您将最终得到一个从零开始的数组,而不是一个从一个开始的数组。坚持使用“下边界”和“上边界”进行循环迭代,可以为自己节省一些痛苦。

简单的行检查将告诉您A列中是否有多个工作表名称。如果是单个值,请分割一个非法的工作表名称字符,最后得到一个元素数组。

Dim All_WorkWeeks_Entered As Variant, counter as long

With Worksheets("workweeks")
    if .Cells(.Rows.Count, "A").End(xlUp).row>1 then
        All_WorkWeeks_Entered = Application.Transpose(.Range(.cells(1, "A"), .Cells(.Rows.Count, "A").End(xlUp)))
    else
        All_WorkWeeks_Entered = split(.Range("A1"), "/")
    end if
End With

For Counter = LBound(All_WorkWeeks_Entered) To UBound(All_WorkWeeks_Entered)
    'do stuff with All_WorkWeeks_Entered(Counter)
Next Counter

答案 1 :(得分:0)

实际上,单成员数组以其类型而不是数组的形式出现。一个好的解决方法是使用IsArray()函数检查数组并采取相应的措施。

Public Sub TestMe()

    Dim alldata As Variant    
    With Worksheets(1)
        'works ok, returning array:
        'alldata = Application.Transpose(.Range("A1:A2"))

        'problematic - does not return an array, but a type not supporting Ubound():
        alldata = Application.Transpose(.Range("A1"))
    End With

    If IsArray(alldata) Then
        Debug.Print UBound(alldata)
    Else
        Debug.Print "Single member array!"
    End If

End Sub

在这种情况下,可以使用某种逻辑来返回单个成员数组:

If IsArray(alldata) Then
    Debug.Print UBound(alldata)
Else
    Debug.Print "Single member array!"
    ReDim alldata(1)
    alldata(1) = Application.Transpose(Worksheets(1).Range("A1"))
    Debug.Print UBound(alldata)
End If

答案 2 :(得分:0)

问题是Range.Value可以是单个Variant或Variants数组,因此在读取这样的值时必须分支:

With Worksheets("workweeks")
    Dim rngTarget As Range: Set rngTarget = .Range(.Range("A1"), .Cells(.Rows.Count, "A").End(xlUp))
    If IsArray(rngTarget.Value) Then
        All_WorkWeeks_Entered = Application.Transpose(rngTarget.Value)
    Else
        Dim varArray(1 To 1) As Variant: varArray(1) = rngTarget.Value
        All_WorkWeeks_Entered = varArray
    End If
End With

第二个循环看起来像这样:

For Counter = LBound(All_WorkWeeks_Entered) To UBound(All_WorkWeeks_Entered)
' ...
Next Counter