收到"超出范围"错误,无法弄清楚原因

时间:2014-07-30 13:47:48

标签: excel vba excel-vba

首先,我要感谢大家的帮助/意图。这个社区是非凡的。第二:我对此非常陌生 - 在本周之前,我在十年前在高中学习基础知识,但除了理论之外没有其他编程经验。

不用多说,这就是我的问题:

使用代码查找唯一变量(我知道那里有很多开源资源,但需要自定义)。当我用第一个字符串填充数组时,我遇到了超出范围的'数组(1)的错误,我明确设置(1 TO UB),UB是上限。我还用msgbox仔细检查了UB的值,并且用我的虚拟数据检查了它的15,所以这不应该成为一个问题。我已将数组中的值设置为空(也使用0表示,但无效)。

错误发生在" ResultArray(1)= CurrentArray(1)"

我不知所措;非常感谢任何协助。

Option Explicit


Sub unque_values()


'''''''''Variable declaration
'
'   CurrentArray() is the array taken from the worksheet
'   Comp is the method of comparing inputs (either case sensitive or case insensitive)
'   resultarray() is the array that unique values are placed
'   UB is the upper bound of Result Array
'   resultindex is the variable that keeps track of which cells are unique and which are not
'   n is a helped variable that assists with resizing the array

Dim currentarray() As Variant
Dim comp As VbCompareMethod
Dim resultarray() As Variant
Dim UB As Long
Dim resultindex As Long
Dim n As Long
Dim v As Variant
Dim inresults As Boolean
Dim m As Long


' set variables to default values
Let comp = vbTextCompare
Let n = 0

' count the number of cells included in currentarray and populate with values
Let n = ActiveWorkbook.Worksheets("Data").Range("A:A").Count
Let UB = ActiveWorkbook.Worksheets("Data").Range("A" & n).End(xlUp).Row



' dimension arrays
ReDim resultarray(1 To UB)
ReDim currentarray(1 To UB)
' don't forget to change to named ranges
Let currentarray() = Range("f2", "f" & UB)



' populate resultarray with empty values

For n = LBound(resultarray) To UBound(resultarray)
resultarray(n) = Empty
Next n



MsgBox (n)



'check for invalid values in array
For Each v In currentarray
    If IsNull(n) = True Then
        resultarray = CVErr(xlErrNull)

        Exit Sub
    End If
Next v


' assumes the first value is unique
resultindex = 1
'''''''''''''''''''''''''''''''''''''''''error is this line''''''''''''''
resultarray(1) = currentarray(1)

' Search for duplicates by cycling through loops
' n = index of value being checked
' m = index of value being checked against
 For n = 2 To UB
    Let inresults = False
    For m = 1 To n
        If StrComp(CStr(resultarray(m)), CStr(currentarray(n)), comp) = 0 Then
            inresults = True
            Exit For
        End If
    Next m

    If inresults = False Then
        resultindex = resultindex + 1
        resultarray(resultindex) = currentarray(n)
    End If
    Next n

ReDim Preserve resultarray(1 To resultindex)




End Sub

2 个答案:

答案 0 :(得分:3)

您已为currentArray指定了范围数组。这些都是二维数组。

enter image description here

你应该可以通过以下方式解决它:

resultarray(1) = currentarray(1, 1)

您需要在代码中修改更多行以引用数组的两个维度。

或者,通过对现有代码的最少操作,转置将其转换为一维数组的数组。这应该不需要对您的代码进行其他更改。

Let currentArray() = Application.Transpose(Range("f2", "f" & UB))

答案 1 :(得分:-1)

尝试使用ActiveWorkbook.Worksheets("Data").UsedRange.Columns(1).cells.Count