静态或动态数组

时间:2014-02-19 17:18:48

标签: vba excel-vba excel

我有以下代码:

Sub nummm()

    Dim num() As String

    For x = 2 To 1000
        c = 0
        ReDim Preserve num(UBound(Split(Cells(x, 7).Value, " ")) + 1)
        num = Split(Cells(x, 7).Value, " ")

        For Each b In num
            c = c + 1
            If c = UBound(num) + 1 Then GoTo vv:
        Next

vv:
    Next

End Sub

如果我删除行

,它运行正常
   If c = UBound(num) + 1 Then GoTo vv:

但如果没有删除,我会得到运行时错误:“此数组已修复或暂时锁定” 如何使变量num动态化? 请求帮助

1 个答案:

答案 0 :(得分:2)

我不知道您的b和其他变量(num除外)是如何声明的,但这可能会对您有所帮助:

Sub nummm()

    Dim num As Variant 'So you can directly assign the array from Split

    For x = 2 To 1000
        c = 0
        num = Split(Cells(x, 7).Value, " ")

        For Each b In num
            c = c + 1

            'Rather than "GoTo somewhere", "Exit For" will exit the current For loop
            If c = UBound(num) + 1 Then Exit For
        Next b

    Next x

End Sub