2017-01-16 195 views
0

我是Excel和VBA编程的新手,我已经创建了考勤表,并希望通过按按钮将数据从一张表复制到另一张表(按月计)。运行时错误'9',下标超出范围错误

,我在下面的行收到错误

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 
+0

@ YowE3K你是对的,我注意到后,谢谢:) –

+0

lastrow2 =表(“sheet2”)。范围(“A”&表(“sheet2”).Rows.Count).End(xlUp)。行 – Kanan

回答

0

你的代码有错误类型的,而不是"

最好远离Activate,SelectActiveSheet,并改用引用的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循环。

+0

@Kanan你在哪一行得到你的错误? –

+0

@Kanan我刚刚测试过它,它适用于我,你确定你的工作簿中有“sheet2”吗?这样拼写? –

+0

@Kanan你从上面复制了我的整个代码?所有的 ?与人; ''''而不是你的'''仍然有这个错误?不能跟踪它,对不起 –

相关问题