Excel宏工作不同的工作表

时间:2017-04-11 01:43:50

标签: excel vba excel-vba

Sub CopyPaste()
    '
    ' CopyPaste Macro
    '
    ' Keyboard Shortcut: Ctrl+Shift+P
    '
        Range("A2:C5").Select
        Selection.Copy
        Sheets("A").Select
        Range("A2").Select
        ActiveSheet.Paste
        Sheets("Sheet1").Select
        Range("A6:C11").Select
        Application.CutCopyMode = False
        Selection.Copy
        Sheets("B").Select
        Range("A2").Select
        ActiveSheet.Paste
        Sheets("Sheet1").Select
        Range("A12:C17").Select
        Application.CutCopyMode = False
        Selection.Copy
        Sheets("C").Select
        Range("A2").Select
        ActiveSheet.Paste
        Sheets("Sheet1").Select
        Range("A18:C21").Select
        Application.CutCopyMode = False
        Selection.Copy
        Sheets("D").Select
        Range("A2").Select
        ActiveSheet.Paste
    End Sub

我尝试制作一个宏来完成一项基本任务,但我似乎无法弄明白,任何人都可以帮忙!我正在尝试创建一个宏,它将从一个工作表中复制数据,并根据特定的字母放入另一个工作表。

例如,所有“A”项目将自动粘贴到新工作表名称“A”中。我可以毫无问题地做到这一点。但是,当我想使用相同的宏与另一行不同的列是我有问题的地方。

我已经使用了录制的宏,然后如果复制工作表中的行已经缩小,它将在新工作表中错误地粘贴。

有什么办法可以解决吗? 提前谢谢。

P / S - >新工作表中将包含标题。所以如果他们可以从A2行开始粘贴就好了。例如,可以参考下面的图片。

enter image description here

1 个答案:

答案 0 :(得分:0)

参见示例/并查看对代码的评论

Option Explicit
Public Sub Example()
    'Declare your Variables
    Dim Sht As Worksheet
    Dim rng As Range
    Dim List As Collection
    Dim varValue As Variant
    Dim i As Long

    With ThisWorkbook
        'Set your Sheet name
        Set Sht = ActiveWorkbook.Sheets("Sheet1")

        'set your auto-filter,  A1
        With Sht.Range("A1")
            .AutoFilter
        End With

        'Set your agent Column range # (1) that you want to filter it
        Set rng = Range(Sht.AutoFilter.Range.Columns(1).Address)

        'Create a new Collection Object
        Set List = New Collection

        'Fill Collection with Unique Values
        On Error Resume Next
        For i = 2 To rng.Rows.Count
            List.Add rng.Cells(i, 1), CStr(rng.Cells(i, 1))
        Next i

        'Start looping in through the collection Values
        For Each varValue In List
            'Filter the Autofilter to macth the current Value
            rng.AutoFilter Field:=1, Criteria1:=varValue
            'Copy the AutoFiltered Range to new Workbook
            Sht.AutoFilter.Range.Copy
            Worksheets.Add.Paste
            ActiveSheet.Name = Left(varValue, 30)
        Next  ' Loop back

        'Go back to main Sheet and removed filters
        Sht.AutoFilter.ShowAllData
        Sht.Activate

    End With
End Sub

确保数据上有标题,请参阅下文

enter image description here