[英]Trying to copy a range from one sheet and paste it to the next empty cell in a column on another sheet
[英]MAC VBA Trying to cut one cell from each worksheet and paste in another sheet in next empty cell
我正在嘗試通過活動工作簿中的每個工作表 go ,其中工作表是作為正在工作的宏的一部分創建的。 每次的名字都可能不同,所以我不能只做查找。 我想獲取一條信息(每個工作表上的相同單元格)並將其粘貼到另一張工作表上的列中的下一個空單元格中。
在第 6 行,我得到錯誤下標超出范圍錯誤 9。我檢查了我要粘貼到的工作表的命名,它是正確的。 沒有多余的空格。
它快把我逼瘋了。 你能幫我嗎?
ps我正在努力在我通常不這樣做的MAC上運行,所以也許我的代碼有點錯誤。
For Each sh In ThisWorkbook.Worksheets
DoEvents
sh.Activate
Range("K5").Select
Selection.Copy
Sheets("Payment Ref").Range("b2").Select
If Range("b2") = "" Then
Range("b2").PasteSpecial Paste:=xlPasteFormats
Range("b2").PasteSpecial Paste:=xlPasteValues
Else
Range("b2").Offset(1, 0).PasteSpecial xlPasteFormats
Range("b2").Offset(1, 0).PasteSpecial xlPasteValues
End If
Next sh
在運行結束時,Payment Ref 電子表格應該有一列填充了在前一個宏部分中創建的發票表中的發票編號。 這完美地工作。
Avoid .Select
and .Activate
(see How to avoid using Select in Excel VBA ) and reference a worksheet for all your ranges (eg using With
).
此外,您每次粘貼時都需要找到最后使用的單元格。 查找列中最后使用的單元格的一個好方法是:
Cells(Rows.Count, "B").End(xlUp) 'last used cell in column B
所以以下應該適合你
Dim wsDestination As Worksheet
Set wsDestination = ThisWorkbook.Worksheets("Payment Ref")
For Each sh In ThisWorkbook.Worksheets
sh.Range("K5").Copy
With wsDestination.Cells(wsDestination.Rows.Count, "B").End(xlUp).Offset(RowOffset:=1)
.PasteSpecial Paste:=xlPasteFormats
.PasteSpecial Paste:=xlPasteValues
End With
Next sh
通常,您應該避免使用.Select
,如評論中所鏈接。 這很可能是您的錯誤的原因。 此外,如果您在超過 1 個或 2 個工作表上執行此代碼(取決於B2
是否已經有一個值),該過程將繼續將這些值放在單元格B3
中。 我建議進行以下更改:
For Each sh In ThisWorkbook.Worksheets
sh.Range("K5").Copy
Sheets("Payment Ref").Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteFormats
Sheets("Payment Ref").Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValues
Next sh
我認為這也應該起作用:
For Each sh In ThisWorkbook.Worksheets
sh.Range("K5").Copy Sheets("Payment Ref").Cells(Rows.Count, 2).End(xlUp).Offset(1, 0)
Next sh
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.