[英]Run time error '9' ,Subscript out of range error
我是Excel和VBA編程的新手,我制作了考勤表,並想通過按按鈕將數據從一張紙復制到另一張紙(逐月)。
我在以下行出現錯誤
lastrow1 = Sheets(“Sheet14”).Range(“A” & Rows.Count).End(xlUp).Row
我的密碼
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
您的代碼的“
而不是"
類型錯誤。
最好不要使用Activate
, Select
和ActiveSheet
而應使用引用的Worksheet和Ranges(它也會更快)。
嘗試下面的代碼,它會執行相同的操作,只是速度要快一點(並且更可靠,這取決於ActiveSheet
。
修改后的代碼
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
注意 :如果sheet2和sheet14中的數據是唯一的(在整個工作表中僅出現一次),請考慮使用Match
函數,它將為您節省1 For
循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.