复制自动过滤范围,vba excel

时间:2013-09-17 18:17:26

标签: excel vba autofilter

我编写了执行以下操作的代码:

  1. 将自动过滤器应用于所选sheet
  2. 中的特定workbook
  3. autofiltered range以外的数据从标题复制到另一个workbook
  4. 以下是代码:

     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

    我该如何解决这个问题?我将感谢您的帮助和答案。

    修改

    以下是工作表中的数据示例

    example of data

    过滤器应用于Criteria1(<> 60,<> 50)和Criteria2(<> 1470,<> 1450)

1 个答案:

答案 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