简体   繁体   中英

Excel VBA arrays creating error 9

I'm writing a sub in VBA that is trying to look at each element in one array and see if it shows up in another array. The first array is in rows A2:A325 in Sheet A, and the second array is over 250,000 values. I keep getting a runtime error 9: subscript out of range. My code is below

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

The line that generates the error is:

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

Any help on how to fix this would be appreciated. I've tried everything I know

When you use Range() to return a range of values into a variant array, the array is resized to match the range. So the results of

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

is that studyDRG will have elements from 1 to 324, not 1 to 325. Not only that, but Range() always returns a two dimensional array, even if there's only one column. So to refer to the element that corresponds to A2, you need to use StudyDRG(1,1), and A3 would be StudyDRG(1,2).

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM