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

我正在筛选工作簿中第一个工作表上的大型数据集,然后在工作簿中为主数据集的第一列中的每个唯一名称创build一个单独的工作表。

在过滤给定名称的主数据集之后,我试图小计一个特定的过滤列(比方说列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 

这里的主要问题是小计函数调用不再在主表单上find引用的单元格。 任何帮助深表感谢。

编辑:

以下现在提供正确的小计。

 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 

最后一行确保删除filter时,可见单元格的原始总和保持不变(而不是将可见单元格与现在删除的filter的总和)。

您有没有尝试在小计公式中包含原始工作表名称作为参考?

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

我用9,C2:C代替了9,C2:C 9, " & wsCurrent.Name & "!C2:C应该适当地引用它。