我编写了执行以下操作的代码:
sheet
workbook
autofiltered range
以外的数据从标题复制到另一个workbook
以下是代码:
m = 2
For i = 1 To work_book.Worksheets.Count
With work_book.Sheets(i)
If (.UsedRange.Rows.Count > 1) Then
'apply filters
.UsedRange.AutoFilter field:=2, Criteria1:=array_of_account_numbers, Operator:=xlFilterValues
.UsedRange.AutoFilter field:=1, Criteria1:=array_of_debit_or_credits, Operator:=xlFilterValues
'select only visible cells after autofilter is applied
On Error Goto a
m = destination_workbook.Sheets(1).UsedRange.Rows.Count + 1
Intersect(.UsedRange, .UsedRange.Offset(1)).SpecialCells(xlCellTypeVisible).Copy destination_workbook.Sheets(1).Range("A" & m)
a:
End If
End With
然而,宏持久地复制一些垃圾。这意味着除了sheet
之外,它还会复制rows
前三个autofiltered range
。
我该如何解决这个问题?我将感谢您的帮助和答案。
修改
以下是工作表中的数据示例
过滤器应用于Criteria1(<> 60,<> 50)和Criteria2(<> 1470,<> 1450)
答案 0 :(得分:1)
.UsedRange
会获取源表上的所有数据,而不仅仅是自动过滤结果下方的数据。
您在Offset
语句中使用的Intersect...Copy
应该是您要忽略的自动过滤结果上方的行数,而不是值1.
如果您知道有多少个标题行:
numHeaderRows = 5
For i = 1 To work_book.Worksheets.Count
With work_book.Sheets(i)
If (.UsedRange.Rows.Count > 1) Then
'apply auto-filters starting at the row directly above the start of the data.
.UsedRange.Offset(numHeaderRows-1).AutoFilter field:=2, Criteria1:=array_of_account_numbers, Operator:=xlFilterValues
.UsedRange.Offset(numHeaderRows-1).AutoFilter field:=1, Criteria1:=array_of_debit_or_credits, Operator:=xlFilterValues
'select only visible cells after autofilter is applied
On Error Goto a
m = destination_workbook.Sheets(1).UsedRange.Rows.Count + 1
Intersect(.UsedRange, .UsedRange.Offset(numHeaderRows)).SpecialCells(xlCellTypeVisible).Copy destination_workbook.Sheets(1).Range("A" & m)
a:
End If
End With
Next