简体   繁体   English

使用VBA将小计复制到Excel中的新工作表

[英]Copying subtotal to a new worksheet in Excel using VBA

I am filtering a large data set on the first sheet in my workbook and then I am creating a separate worksheet in the workbook for each unique name in the first column of the main data set. 我在工作簿的第一张工作表上过滤了一个大型数据集,然后在工作簿中为主数据集的第一列中的每个唯一名称创建了一个单独的工作表。

After I filter the main data set for a given name, I am attempting to subtotal a particular filtered column (let's say column C), for example: 在为给定名称过滤了主要数据集之后,我尝试对总计的特定过滤列(例如C列)进行小计,例如:

Sub CreateSheets()

    Dim wsCurrent As Worksheet
    Dim wsNew As Worksheet
    Dim iLeft As Integer
    Dim length As Long

    Set wsCurrent = ActiveSheet
    Application.ScreenUpdating = False

    'Copy list of all players and remove duplicates
    Range("A2", Range("A2").End(xlDown)).Copy Range("AY1")
    Range("AY1").CurrentRegion.RemoveDuplicates Columns:=1, Header:=xlYes

    'Iterator
    iLeft = Range("AY1").CurrentRegion.Rows.Count - 1

    'For each player
    Do While iLeft > 13
        Set wsNew = Worksheets.Add
        With wsCurrent.Range("A2").CurrentRegion
            'Player name from copied list
            .AutoFilter Field:=1, Criteria1:=wsCurrent.Range("AY1").Offset(iLeft).Value

            'Hits
            .AutoFilter Field:=3, Criteria1:="1"
            length = .Range("C" & Rows.Count).End(xlUp).Row
            wsNew.Range("A1") = "=SUBTOTAL(9," & wsCurrent.Name & "!C2:C" & length & ")"

            'Turn off filters
            '.AutoFilter
        End With
        'Name player sheet and move onto next
        wsNew.Name = wsCurrent.Range("AY1").Offset(iLeft).Value
        iLeft = iLeft - 1
    Loop

    'Clear player names in copied region
    wsCurrent.Range("AY1").CurrentRegion.Clear
    Application.ScreenUpdating = True

End Sub

The main issue here is that the subtotal function call no longer find the referenced cell on the main sheet. 这里的主要问题是小计函数调用不再在主表上找到引用的单元格。 Any help is much appreciated. 任何帮助深表感谢。

EDIT: 编辑:

The following now provides the correct subtotal. 现在,以下内容提供了正确的小计。

length = .Range("C" & Rows.Count).End(xlUp).Row
wsNew.Range("A1") = "=SUBTOTAL(9," & wsCurrent.Name & "!C2:C" & length & ")"
wsNew.Range("A1").Value = wsNew.Range("A1").Value

The last line ensures that when the filter is removed, the original sum of the visible cells remains (instead of then taking the sum of the visible cells with the filter now removed). 最后一行确保在删除过滤器后,保留可见单元格的原始总数(而不是在删除了过滤器的情况下取可见单元格的总和)。

Have you tried including the original sheet name as a reference in the Subtotal formula? 您是否尝试过将原始工作表名称包含在小计公式中作为参考?

wsNew.Range("A1") = "=SUBTOTAL(9," & wsCurrent.Name & "!C2:C" & length & ")"

I replaced 9,C2:C with 9, " & wsCurrent.Name & "!C2:C which should reference it properly. 我用9, " & wsCurrent.Name & "!C2:C替换了9,C2:C 9, " & wsCurrent.Name & "!C2:C ,应该正确地引用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM