使用 VBA 将数据从主工作表传输到基于列的多个工作表

Posted

技术标签:

【中文标题】使用 VBA 将数据从主工作表传输到基于列的多个工作表【英文标题】:Transfer Data from a Master Worksheet to Multiple Worksheets based on Column using VBA 【发布时间】:2017-04-21 17:01:35 【问题描述】:

我是 VBA 的新手,我正在尝试以 excel 格式获取银行信息,并按每个 excel 电子表格的帐户对其进行分解。我正在第一张表上输入银行数据(所有帐户合并在一个电子表格中)。我想将 VBA 用于 8 个附加选项卡,以分解每个帐户的银行详细信息。

银行数据表 1 列: -帐户类型 -日期 -路由 -户口号码。 -货币 -帐户名称* -交易代码 -交易类型 -交易价值 - 交易记录 -添加注释 -细节 -杂项 -misc(N列是数据的结尾)

我希望 VBA 根据帐户名称拆分银行数据,并保留所有与 sheet1 相同的列。我认为我的查询与此类似:Transfer Data from a Master Worksheet to Multiple based on Column using VBA 但我很难理解该解决方案如何适用于我的案例(而且我的数据几乎没有这个人那么多;在给定的工作表中,我最多可能只有大约 5000 行数据)。

有人可以提供帮助或指出正确的方向吗?

谢谢。

【问题讨论】:

快速搜索你的标题会给我 9 个网页和一个关于如何做到这一点的视频。你有尝试过什么吗? 【参考方案1】:

这当然可以用 VBA 完成。

但是有一种更简单的方法,您是否熟悉数据透视表?

1 创建你的数据透视表,让它看起来不错

2 添加帐号作为过滤器

3 在功能区中,找到数据透视表选项并按向下箭头,然后单击“显示报表过滤器页面”。

【讨论】:

我确实使用数据透视表,一旦我根据这些银行数据对它们进行核对,我就会格式化交易以进行注释。我不确定数据透视表会在那种情况下工作吗?我可能会弄乱它,谢谢你的建议!【参考方案2】:

我认为这会满足您的需求。

Sub Copy_To_Worksheets()
'Note: This macro use the function LastRow
    Dim My_Range As Range
    Dim FieldNum As Long
    Dim CalcMode As Long
    Dim ViewMode As Long
    Dim ws2 As Worksheet
    Dim Lrow As Long
    Dim cell As Range
    Dim CCount As Long
    Dim WSNew As Worksheet
    Dim ErrNum As Long

    'Set filter range on ActiveSheet: A1 is the top left cell of your filter range
    'and the header of the first column, D is the last column in the filter range.
    'You can also add the sheet name to the code like this :
    'Worksheets("Sheet1").Range("A1:D" & LastRow(Worksheets("Sheet1")))
    'No need that the sheet is active then when you run the macro when you use this.
    Set My_Range = Range("A1:D" & LastRow(ActiveSheet))
    My_Range.Parent.Select

    If ActiveWorkbook.ProtectStructure = True Or _
       My_Range.Parent.ProtectContents = True Then
        MsgBox "Sorry, not working when the workbook or worksheet is protected", _
               vbOKOnly, "Copy to new worksheet"
        Exit Sub
    End If

    'This example filters on the first column in the range(change the field if needed)
    'In this case the range starts in A so Field:=1 is column A, 2 = column B, ......
    FieldNum = 1

    'Turn off AutoFilter
    My_Range.Parent.AutoFilterMode = False

    'Change ScreenUpdating, Calculation, EnableEvents, ....
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    ActiveSheet.DisplayPageBreaks = False

    'Add a worksheet to copy the a unique list and add the CriteriaRange
    Set ws2 = Worksheets.Add

    With ws2
        'first we copy the Unique data from the filter field to ws2
        My_Range.Columns(FieldNum).AdvancedFilter _
                Action:=xlFilterCopy, _
                CopyToRange:=.Range("A1"), Unique:=True

        'loop through the unique list in ws2 and filter/copy to a new sheet
        Lrow = .Cells(Rows.Count, "A").End(xlUp).Row
        For Each cell In .Range("A2:A" & Lrow)

            'Filter the range
            My_Range.AutoFilter Field:=FieldNum, Criteria1:="=" & _
             Replace(Replace(Replace(cell.Value, "~", "~~"), "*", "~*"), "?", "~?")

            'Check if there are no more then 8192 areas(limit of areas)
            CCount = 0
            On Error Resume Next
            CCount = My_Range.Columns(1).SpecialCells(xlCellTypeVisible) _
                     .Areas(1).Cells.Count
            On Error GoTo 0
            If CCount = 0 Then
                MsgBox "There are more than 8192 areas for the value : " & cell.Value _
                     & vbNewLine & "It is not possible to copy the visible data." _
                     & vbNewLine & "Tip: Sort your data before you use this macro.", _
                       vbOKOnly, "Split in worksheets"
            Else
                'Add a new worksheet
                Set WSNew = Worksheets.Add(After:=Sheets(Sheets.Count))
                On Error Resume Next
                WSNew.Name = cell.Value
                If Err.Number > 0 Then
                    ErrNum = ErrNum + 1
                    WSNew.Name = "Error_" & Format(ErrNum, "0000")
                    Err.Clear
                End If
                On Error GoTo 0

                'Copy the visible data to the new worksheet
                My_Range.SpecialCells(xlCellTypeVisible).Copy
                With WSNew.Range("A1")
                    ' Paste:=8 will copy the columnwidth in Excel 2000 and higher
                    ' Remove this line if you use Excel 97
                    .PasteSpecial Paste:=8
                    .PasteSpecial xlPasteValues
                    .PasteSpecial xlPasteFormats
                    Application.CutCopyMode = False
                    .Select
                End With
            End If

            'Show all data in the range
            My_Range.AutoFilter Field:=FieldNum

        Next cell

        'Delete the ws2 sheet
        On Error Resume Next
        Application.DisplayAlerts = False
        .Delete
        Application.DisplayAlerts = True
        On Error GoTo 0

    End With

    'Turn off AutoFilter
    My_Range.Parent.AutoFilterMode = False

    If ErrNum > 0 Then
        MsgBox "Rename every WorkSheet name that start with ""Error_"" manually" _
             & vbNewLine & "There are characters in the name that are not allowed" _
             & vbNewLine & "in a sheet name or the worksheet already exist."
    End If

    'Restore ScreenUpdating, Calculation, EnableEvents, ....
    My_Range.Parent.Select
    ActiveWindow.View = ViewMode
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
        .Calculation = CalcMode
    End With

End Sub


Function LastRow(sh As Worksheet)
    On Error Resume Next
    LastRow = sh.Cells.Find(What:="*", _
                            After:=sh.Range("A1"), _
                            Lookat:=xlPart, _
                            LookIn:=xlValues, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Row
    On Error GoTo 0
End Function

http://www.rondebruin.nl/win/s3/win006_4.htm

【讨论】:

以上是关于使用 VBA 将数据从主工作表传输到基于列的多个工作表的主要内容,如果未能解决你的问题,请参考以下文章

通过工作簿VBA从主列表更新价格

将excel工作表数据从excel vba传输到访问表给出错误

Excel VBA 在工作表中插入/删除行

VBA代码根据列的内容将excel文件拆分为多个工作簿?

VBA将数组传输到工作表

如何使用 Excel VBA 将特定行从多个工作表复制到另一个工作表?