Visual Basic:运行时错误'9':“下标超出范围”

时间:2016-03-07 11:01:59

标签: excel vba excel-vba basic

我正在尝试创建一个脚本,可以删除数字列表中的重复项。唯一的问题是,我一直在Subscript out of range (Error 9)

Sub remDupes()
Dim units() As Variant
For i = 2 To 37
    Dim var As String
    If ((Not Not units) = 0) Then
        For x = 0 To 36
            var = Cells(i, 22).Value
            If (units(x) = var) Then
                Range("V" & i, "AA" & i).Value = ""
            Else
                units(x) = var
            End If
        Next
    End If
Next
End Sub

错误发生在:

If (units(x) = var) Then

而且我不确定为什么

1 个答案:

答案 0 :(得分:0)

您需要在触发错误的行之前添加以下行。

ReDim Preserve units(0 To x)

新代码将如下所示。

Sub remDupes()
Dim units() As Variant
For i = 2 To 37
    Dim var As String
    If ((Not Not units) = 0) Then
        For x = 0 To 36
            var = Cells(i, 22).Value
            ReDim Preserve units(0 To x)
            If (units(x) = var) Then
                Range("V" & i, "AA" & i).Value = ""
            Else
                units(x) = var
            End If
        Next
    End If
Next
End Sub