2017-09-19 115 views
0

我看過一些例子,但他們一直在使用.Select和.Activate。我正在嘗試學習如何不再使用它們,因爲大家都說你應該儘量遠離它們。從一張紙粘貼到另一張到第一個空行

我想取一排,然後將其複製到另一張紙上的第一個空白行。我很近,但它不工作。

UsdRws = Range("A" & Rows.Count).End(xlUp).Row 


With Sheets("Totals by Department") 
    .Range("A1:Z" & UsdRws).autofilter Field:=1, Criteria1:="1450" 
    .Range("A2:Z" & UsdRws).SpecialCells(xlCellTypeVisible).EntireRow.COPY 
End With 


Set NextRow = Range("A" & Sheets(2).UsedRange.Rows.Count + 1) 


Sheets(2).NextRow.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False 
    Application.CutCopyMode = False 

Set NextRow = Nothing 

第一部分完美複製,我真的只需要幫助粘貼在另一張紙上。我還會採取其他建議來清理代碼。就像我說的,我正在努力學習寫得更好。第二部分很混亂,因爲我一直在添加和編輯它,但現在我迷了路。

回答

2

您的「NextRow」對象是一個Range對象,但您將它稱爲Sheets(2)的方法或屬性。

嘗試刪除表單(2)。並從下一行開始。

Set NextRow = Sheets(2).Range("A" & Sheets(2).UsedRange.Rows.Count + 1) 
NextRow.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False 
Application.CutCopyMode = False 
+0

什麼它看起來就在我複製粘貼的地方。它不會轉到另一張紙上。我必須實際選擇它嗎?或激活它? – Robillard

+0

我剛編輯過這個,再試一次。您的原始代碼不符合NextRow屬於哪張表,因此Excel會自動將其設置爲ActiveSheet。通過將其定義爲表格(2).Range,它將複製到正確的表單。 – Smith

+0

謝謝!非常棒!在我即將離開工作之前。現在我不會整夜想到這件事 – Robillard

0
' UsdRws is equal the last used row on whichever sheet is active at the moment that this code runs 

UsdRws = Range("A" & Rows.Count).End(xlUp).Row 

' this code properly references ranges on a specific worksheet, regardless of which worksheet is active 

With Sheets("Totals by Department") 
    .Range("A1:Z" & UsdRws).autofilter Field:=1, Criteria1:="1450" 
    .Range("A2:Z" & UsdRws).SpecialCells(xlCellTypeVisible).EntireRow.COPY 
End With 

' NextRow is reference to a cell on whichever sheet is active at the moment that this code runs 
' but the row referenced is same as the first emply cell on Sheets(2) 

Set NextRow = Range("A" & Sheets(2).UsedRange.Rows.Count + 1) 

' NextRow is already a range .... so it should be NextRow.PasteSpecial ...... 

Sheets(2).NextRow.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False 
    Application.CutCopyMode = False 

Set NextRow = Nothing 

這可能是你想要

With Sheets("Totals by Department") 
    UsdRws = .Range("A" & .Rows.Count).End(xlUp).Row 
    .Range("A1:Z" & UsdRws).autofilter Field:=1, Criteria1:="1450" 
    .Range("A2:Z" & UsdRws).SpecialCells(xlCellTypeVisible).EntireRow.COPY 
End With 

Set NextRow = Sheets(2).Range("A" & Sheets(2).UsedRange.Rows.Count + 1) 

NextRow.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False 

Application.CutCopyMode = False 

Set NextRow = Nothing 
相關問題