2017-01-16 156 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你從上面複製了我的整個代碼?所有的 ?與人; ''''而不是你的'''仍然有這個錯誤?不能跟蹤它,對不起 –