如果不相交,Excel VBA的内存使用过多吗?

时间:2019-05-09 12:24:45

标签: excel vba

我的工作簿包含一张工作表,其中包含约50列x 50行的公式。文件本身大约有500kB,没有限制。格式化,我尽可能避免使用易失性函数。当我打开工作簿时,Excel的内存使用量约为180MB,但是当我更改重新计算工作表的单元格值时,它将增加到2.8GB。我唯一的VBA代码是:

seetest.swipe("Right", 10, 500);

我怀疑这段代码并不完美,会使内存混乱。是否可以对其进行优化以减少内存使用?

1 个答案:

答案 0 :(得分:0)

您正在寻找的东西似乎是这样的:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim rChanged As Range

    Set rChanged = Intersect(Target, Me.Range("M4", Me.Cells(Me.Rows.Count, "M")))
    If Not rChanged Is Nothing Then
        With Application
            .Calculation = xlCalculationManual
            .ScreenUpdating = False
            .EnableEvents = False
        End With

        Dim ChangedCell As Range
        Dim rDest As Range
        Dim rClear As Range
        For Each ChangedCell In rChanged.Cells
            If Len(ChangedCell.Value) > 0 Then
                Select Case (rDest Is Nothing)
                    Case True:  Set rDest = Me.Cells(ChangedCell.Row, "T")
                    Case Else:  Set rDest = Union(rDest, Me.Cells(ChangedCell.Row, "T"))
                End Select
            Else
                Select Case (rClear Is Nothing)
                    Case True:  Set rClear = Me.Cells(ChangedCell.Row, "T").Resize(, Me.Range("T:BD").Columns.Count)
                    Case Else:  Set rClear = Union(rClear, Me.Cells(ChangedCell.Row, "T").Resize(, Me.Range("T:BD").Columns.Count))
                End Select
            End If
        Next ChangedCell

        If Not rDest Is Nothing Then Me.Range("T4:BD4").Copy rDest
        If Not rClear Is Nothing Then rClear.ClearContents

        With Application
            .Calculation = xlCalculationAutomatic
            .ScreenUpdating = True
            .EnableEvents = True
        End With
    End If

End Sub