2016-06-10 200 views
0

以下腳本看起來應該可以正常工作,但我在下面標記的行上收到「對象已定義」錯誤。我找不到是什麼原因...將行從一張紙複製到另一張

Sub MailMerge() 
Sheets.Add.Name = "MailMerge" 
Dim MailMerge As Worksheet 
Set MailMerge = Sheets("MailMerge") 
Dim Rng As Range 
Dim i, index, lastrow As Long 
Dim Abstracts As Worksheet 
Set Abstracts = Sheets("Abstracts") 

lastrow = Abstracts.Cells(Rows.Count, 1).End(xlUp).row 


For i = 1 To lastrow 
    Set Rng = Abstracts.Range("O" & i) 
     If WorksheetFunction.CountA(Rng) >= 1 Then 
      Abstracts.Range("A" & i).Resize(0, 14).Copy _ 
      Destination:=MailMerge.Range("A" & i).Resize(0, 14) 
      'this is where the error is occuring 
     End If 
Next 

End Sub 

有什麼建議嗎?

+0

您是否需要調整粘貼大小? – findwindow

+0

可能不是。但是,刪除調整大小並不能解決問題。 – user1996971

回答

1

調整大小不像OFFSET。它會將範圍的大小設置爲規定的大小。所以你將範圍大小設置爲0行。它應該是1:

Sub MailMerge() 
Sheets.Add.Name = "MailMerge" 
Dim MailMerge As Worksheet 
Set MailMerge = Sheets("MailMerge") 
Dim Rng As Range 
Dim i, index, lastrow As Long 
Dim Abstracts As Worksheet 
Set Abstracts = Sheets("Abstracts") 

lastrow = Abstracts.Cells(Rows.Count, 1).End(xlUp).Row 


For i = 1 To lastrow 
    Set Rng = Abstracts.Range("O" & i) 
     If WorksheetFunction.CountA(Rng) >= 1 Then 
      Abstracts.Range("A" & i).Resize(1, 14).Copy _ 
      Destination:=MailMerge.Range("A" & i).Resize(1, 14) 
      'this is where the error is occuring 
     End If 
Next 

End Sub 
+0

完美。這解決了這個問題。我沒有意識到這種方式調整大小。我總是想知道爲什麼Resize總是好像在'包含'當前的單元格,而'Offset'則沒有。現在我明白了! :) – user1996971

相關問題