简体   繁体   中英

Runtime Error 9 : Subcript out of range

I'm trying to write a vba code to check if workbook(A).worksheet(a).cells(row1, colum1) = workbook (B).worksheet(b).cells(row2,colum2), then do some copying and further checking. But encounter an error message "subscript out of range". Would anyone please help me on this?

Following is the code:

Sub check()
    Dim row1, row2, row1start, row2start, row1end, row2end
    Dim ws1 As Worksheet
    ws1 = Excel.Workbooks("A.xlsx").Worksheets("sheet1")
    Dim ws2 As Worksheet
    ws2 = Excel.Workbooks("B.xlsx").Worksheets("sheet2")
    row1start = 2
    row1end = 43
    row2start = 3
    row2end = 163
    For row1 = row1start To row1end
        For row2 = row2start To row2end
            If ws2.Cells(row2, "I") = ws1.Cells(row1, "H") Then
                ws1.Cells(row1, "I") = 0    'mark true
                ws1.Cells(row1, "M") = ws2.Cells(row2, "K")     'copy

                If ws1.Cells(row1, "C") = ws2.Cells(row2, "J") Then
                    ws1.Cells(row1, "N") = 0    'mark true
                Else
                    ws1.Cells(row1, "N") = ws2.Cells(row2, "J")     'copy
                End If
                Exit For    'if found, then exit 1st loop
            End If
        Next row2

        If row2 >= row2end Then     'if no match, assign value -1
            ws1.Cells(row1, "I") = -1
        End If

        If row2start < row2end Then     'reduce searching times for next row1
            row2start = row2 + 1
        End If   
    Next row1
End Sub

Subscript out of range means it can't find the specified workbook, worksheet or range. Check, double check and recheck your names. If you're getting the error on this: ws1 = Excel.Workbooks("A.xlsx").Worksheets("sheet1") try isolating the assignment of the workbook and the worksheet to find which is giving the error.

Just found the same thing as Rory; You must use SET for workbook, worksheet or range; or any object.

SET ws1 = Excel.Workbooks("A.xlsx").Worksheets("sheet1")

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