[英]VBA - Copy only visible cells from sheet to another worksheet
我有工作表(“格式化數據”)和工作表(“ Client_1數據”)
我運行宏,它執行以下步驟:
我的問題是什么:
我的宏代碼:
Sub PRINT_AVIVA_ISA()
Sheets("Formatted Data").Select
ActiveSheet.Range("$A$1:$R$73").autofilter Field:=3, Criteria1:=Array( _
"client_1"), Operator:=xlFilterValues
Dim LastRow As Long, erow As Long
LastRow = Worksheets("Formatted Data").Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To LastRow
Worksheets("Formatted Data").Cells(i, 2).Copy
erow = Worksheets("Client_1 Data").Cells(Rows.Count, 1).End(xlUp).Row
Worksheets("Formatted Data").Paste Destination:=Worksheets("Client_1 Data").Cells(erow + 1, 1) ' --- account number
Worksheets("Formatted Data").Cells(i, 3).Copy
Worksheets("Formatted Data").Paste Destination:=Worksheets("Client_1 Data").Cells(erow + 1, 2) ' --- designation
Worksheets("Formatted Data").Cells(i, 4).Copy
Worksheets("Formatted Data").Paste Destination:=Worksheets("Client_1 Data").Cells(erow + 1, 3) ' --- fund name
Worksheets("Formatted Data").Cells(i, 5).Copy
Worksheets("Formatted Data").Paste Destination:=Worksheets("Client_1 Data").Cells(erow + 1, 4) ' --- fund code
Worksheets("Formatted Data").Cells(i, 7).Copy
Next i
End Sub
我需要的:
謝謝,
彼得
您遇到的問題是您正在遍歷“格式化數據”工作表中的所有單元格。 VBA代碼不檢查單元格是否已過濾。
我在下面附加了一些代碼,該代碼應該可以完成您要嘗試執行的操作。 我進行了一些更改以對其進行清理,例如將工作表存儲到它們自己的變量中,這樣您就不必反復地直接引用它們。
另外,我選擇使用直接值分配,而不是復制/粘貼。 直接分配值通常更快,並且具有更清晰,更具描述性的代碼。 折衷方案是它不會復制格式。 如果確實需要格式化,則可以一次添加一次(對於整個列,可以在例程的開頭或結尾)。
查看您是否可以改編以下代碼,並在需要更多幫助時告知我們。
Sub PRINT_AVIVA_ISA()
Dim sData As Worksheet
Dim sClient As Worksheet
'Prevents the application from rendering graphical elements during processing
Application.ScreenUpdating = False
Set sData = Worksheets("Formatted Data")
Set sClient = Worksheets("Client_1 Data")
sData.Range("$A$1:$R$73").AutoFilter Field:=3, Criteria1:=Array( _
"client_1"), Operator:=xlFilterValues
LastRow = sData.Cells(Rows.Count, 1).End(xlUp).Row
Dim i As Long
For i = 2 To LastRow
If sData.Rows(i).Hidden = False Then
' Rather than add 1 to erow 4 times later, just calculate it here
erow = sClient.Cells(Rows.Count, 1).End(xlUp).Row + 1
sClient.Cells(erow, 1).Value = sData.Cells(i, 2).Value
sClient.Cells(erow, 2).Value = sData.Cells(i, 3).Value
sClient.Cells(erow, 3).Value = sData.Cells(i, 1).Value
End If
Next i
Application.ScreenUpdating = True
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.