[英]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. 我正在尝试编写VBA代码来检查workbook(A).worksheet(a).cells(row1,colum1)= workbook(B).worksheet(b).cells(row2,colum2),然后进行一些复制并进一步检查。 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. 如果您遇到此错误:
ws1 = Excel.Workbooks("A.xlsx").Worksheets("sheet1")
尝试隔离工作簿和工作表的分配,以找出产生错误的原因。
Just found the same thing as Rory; 刚发现和Rory一样的东西; You must use
SET
for workbook, worksheet or range; 您必须对工作簿,工作表或范围使用
SET
; or any object. 或任何物体。
SET ws1 = Excel.Workbooks("A.xlsx").Worksheets("sheet1")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.