[英]Run time error '9' ,Subscript out of range error
I am new to Excel and VBA programming, I have made attendance sheet and want to copy data from one sheet to other ( month wise) by pressing button. 我是Excel和VBA编程的新手,我制作了考勤表,并想通过按按钮将数据从一张纸复制到另一张纸(逐月)。
I am getting error at the following line 我在以下行出现错误
lastrow1 = Sheets(“Sheet14”).Range(“A” & Rows.Count).End(xlUp).Row
My code 我的密码
Sub Button2_Click()
Dim i As Long, j As Long, lastrow1 As Long, lastrow2 As Long
Dim myname As String
lastrow1 = Sheets(“Sheet14”).Range(“A” & Rows.Count).End(xlUp).Row
For i = 7 To lastrow1
myname = Sheets(“Sheet14”).Cells(i, “A”).Value
Sheets(“sheet2”).Activate
lastrow2 = Sheets(“sheet2”).Range(“A” & Rows.Count).End(xlUp).Row
For j = 7 To lastrow2
If Sheets(“sheet2”).Cells(j, “A”).Value = myname Then
Sheets(“Sheet14”).Activate
Sheets(“Sheet14”).Range(Cells(i, “D”), Cells(i, “AH”)).Copy
Sheets(“sheet2”).Activate
Sheets(“sheet2”).Range(Cells(j, “D”), Cells(j, “AH”)).Select
ActiveSheet.Paste
End If
Next j
Application.CutCopyMode = False
Next i
Sheets(“Sheet14”).Activate
Sheets(“Sheet14”).Range(“D7”).Select
End Sub
Your code had the wrong type of “
, instead of "
. 您的代码的
“
而不是"
类型错误。
It's better to stay away from Activate
, Select
and ActiveSheet
and use referenced Worksheet and Ranges instead (it will also be faster). 最好不要使用
Activate
, Select
和ActiveSheet
而应使用引用的Worksheet和Ranges(它也会更快)。
Try the code below, it will do the same, just a little faster (and more reliable not depending on the ActiveSheet
. 尝试下面的代码,它会执行相同的操作,只是速度要快一点(并且更可靠,这取决于
ActiveSheet
。
Modified Code 修改后的代码
Sub Button2_Click()
Dim i As Long, j As Long, lastrow1 As Long, lastrow2 As Long
Dim myname As String
With Sheets("Sheet14")
lastrow1 = .Range("A" & .Rows.Count).End(xlUp).Row
' take the line below outside the For loop, there is no need to get the last row evey time
lastrow2 = Sheets("sheet2").Range("A" & Sheets("sheet2").Rows.Count).End(xlUp).Row
For i = 7 To lastrow1
myname = .Range("A" & i).Value
For j = 7 To lastrow2
If Sheets("sheet2").Range("A" & j).Value = myname Then
.Range("D" & i & ":AH" & i).Copy Destination:=Sheets("sheet2").Range(Range("D" & j & ":AH" & j))
End If
Next j
Application.CutCopyMode = False
Next i
End With
End Sub
Note : if the data in sheet2 and sheet14 are unique (appear only once in the entire sheet) consider using the Match
function, it will save you 1 For
loop. 注意 :如果sheet2和sheet14中的数据是唯一的(在整个工作表中仅出现一次),请考虑使用
Match
函数,它将为您节省1 For
循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.