Excel VBA数组创建错误9

时间:2017-03-24 03:31:15

标签: arrays excel-vba vba excel

我正在VBA中编写一个子程序,它试图查看一个数组中的每个元素,看看它是否显示在另一个数组中。第一个数组位于表A中的行A2:A325中,第二个数组超过250,000个值。我不断收到运行时错误9:下标超出范围。我的代码在

之下
Private Sub ICD_DRG_Converter()

Dim StudyDRG() As Variant
Dim StudyICD10() As Variant
Dim element As String
Dim lLastRow, i, j, k As Long
Dim ICD10Code As String


Worksheets("Accepted DRG's").Activate

ReDim StudyDRG(1 To 325) As Variant

StudyDRG = Range("A2:A325") 'Populate the study DRG's into an array for comparison

Worksheets("full_appendix_B").Activate
lLastRow = ActiveSheet.Cells(Rows.Count, "B").End(xlUp).Row 'get the last row of data for sizing our ICD 10 array

ReDim StudyICD10(1 To (lLastRow)) As Variant

StudyICD10 = Range("B2:B" & lLastRow)

'i = 0
For i = LBound(StudyICD10) To UBound(StudyICD10)
    k = 1
    For j = LBound(StudyDRG) To UBound(StudyDRG)
        If StrComp(StudyICD10(i), StudyDRG(j), vbBinaryCompare) = 0 Then 'match between study DRG and ICD-10 DRG
            Worksheets("full_appendix_B").Activate
            ICD10Code = Range("A" & j).Value
            Worksheets("Accepted ICD-10").Activate
            Range("A" & k) = ICD10Code
            k = k + 1
            Exit For
        End If
    Next j
Next i





End Sub

生成错误的行是:

If StrComp(StudyICD10(i), StudyDRG(j), vbBinaryCompare) = 0 Then

如何解决这个问题的任何帮助将不胜感激。我尝试了所有我知道的事情

1 个答案:

答案 0 :(得分:1)

使用Range()将一系列值返回到变量数组时,将调整数组大小以匹配范围。所以结果

ReDim StudyDRG(1 To 325) As Variant
StudyDRG = Range("A2:A325") 

是studyDRG的元素从1到324,而不是1到325。 不仅如此,Range()总是返回一个二维数组,即使只有一列。因此,要引用与A2对应的元素,您需要使用StudyDRG(1,1),而A3将是StudyDRG(1,2)。

我希望这会有所帮助。