运行 向下钻取脚本时出现内存不足错误

Out of Memory Error when running Drill Down Script

宏的目的是避免每次用户双击/向下钻取数据透视表 table 值时创建新作品sheet。相反,脚本将数据复制到专用的“DrillDown”sheet.

点击几次后,我收到一个 Excel 错误,提示我内存不足。

原始数据集不是很大。
我想知道脚本是否有问题,或者我是否需要进一步添加一些内容?
也许我需要先清除一些临时数据?

我的代码:

模块 1

Public CS$

这本练习册

Private Sub Workbook_NewSheet(ByVal Sh As Object)
If CS <> "" Then
    With Application
        ScreenUpdating = False
        Dim NR&
        With Sheets("DrillDown")

            'Set this to always start at the top of the page
            NR = 1
            '..and to clear the Drilldown tab..
            .Cells.ClearContents

            'instead of this..
            'If WorksheetFunction.CountA(.Rows(1)) = 0 Then
            '   NR = 1
            'Else
            '   NR = .Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row + 2
            'End If

            Range("A4").CurrentRegion.Copy .Cells(NR, 1)

        End With
        .DisplayAlerts = False
        ActiveSheet.Delete
        .DisplayAlerts = True
        'Below is commented out to stop user being returned to Pivot
        ' Sheets(CS).Select
    .ScreenUpdating = True
    End With
End If
End Sub

可能是数据仍在写入sheet时事件触发。您可以保留新创建的 sheet 并删除之前的以避免复制。

Private Sub Workbook_NewSheet(ByVal Sh As Object)

    If CS = "" Then Exit Sub
    With Application
        .DisplayAlerts = False
        On Error Resume Next
        Sheets("DrillDown").Delete
        Sh.Name = "DrillDown" ' renamenew sheet
        On Error GoTo 0
        .DisplayAlerts = True
    End With
   
End Sub