收到“超出范围”的错误,不知道为什么

让我首先感谢大家的帮助/意图。 这个社区是惊人的。 第二:我非常新,在这个星期之前,我在十年前就已经在高中学到了基本知识,但除了理论之外没有其他的编程经验。

不用再后悔了,这是我的问题:

处理代码来find唯一的variables(我知道有很多开源的东西,需要定制这个虽然)。 当我用第一个string填充数组时,我遇到了数组(1)处的'超出范围'的错误,我已经明确地设置了(1 TO UB),UB是上限。 我也仔细检查了UB的值与msgbox,它是在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 

你已经分配给currentArray一个范围数组。 这些都是二维数组。

在这里输入图像说明

你应该能够解决它:

 resultarray(1) = currentarray(1, 1) 

您需要修改代码中的几行来引用数组的两个维度。

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

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

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