VBA将循环内的表复制到新工作表

时间:2016-07-18 12:07:58

标签: excel vba filter copy

我有一张桌子,有很多列。我想通过一个特定列中出现的一些值一个接一个地过滤表。一旦表被过滤(对于一个值),我想将结果复制到新工作表并继续使用第二个值。 (实际上我想将它复制到一个新的工作簿并保存,但这是下一步。)

这是我的代码:

'Start Loop
Public Sub LP()


    Dim years As Variant
    Dim number As Variant

    'Array for loop
    years = Array("2013", "20131", "20132")
    For Each number In years

        ' filter definition (filter by number)
        Dim i As Integer, rngData As Range
        Set rngData = Range("A1").CurrentRegion
        i = Application.WorksheetFunction.Match("ColumnXY", Range("A1:BM1"), 0)
        rngData.AutoFilter field:=i, Criteria1:=number


        'Copy filtered data to new sheet
        Dim rng As Range
        Dim WS As Worksheet
        For Each row In Range("Tabelle1[#All]").Rows
            If row.EntireRow.Hidden = False Then
                If rng Is Nothing Then Set rng = row
                Set rng = Union(row, rng)
            End If
        Next row

        Set WS = Sheets.Add
        rng.copy Destination:=WS.Range("A1")

        'Delete specific columns in the new sheet
        WS.Range("A:AD,AP:AQ,AS:BE,BG:BH,BJ:BK").EntireColumn.Delete

        'Autofit Column
        Columns("A:N").Select
        Range(Selection, Selection.End(xlToRight)).Select
        Cells.EntireColumn.AutoFit

        'Tabelle1=1 active table
        Sheets("Tabelle1").Select

        'Remove filter and show all data
        If ActiveSheet.FilterMode Then
        ActiveSheet.ShowAllData
        End If

    'go on with next number
    Next number
End Sub

运行脚本后将生成3张表格,第一张表格正常(2013年的所有数据)。第二张纸不幸地包含来自frist两个数字(2013和20131)的所有行,第三张纸包含来自所有数字的数据。我打算单独为一个数字获取一张数据表,我看不出,有什么不对......

感谢您的帮助!

0 个答案:

没有答案