从表单中删除命令按钮和行非常慢

时间:2015-10-20 23:54:57

标签: excel performance vba excel-vba

此子目录删除在工作表上以编程方式创建的所有命令按钮及其关联的行。删除60个命令按钮和行大约需要20秒。我已经逐步完成了它并且没有发现任何问题。

Sub ResetForm_Click()

    Dim Contr
    Dim controlname As String
    Dim WS As Worksheet

    Set WS = ActiveSheet

        For Each Contr In WS.OLEObjects

        controlname = Mid(Contr.Name, 1, 2)

            If controlname = "CB" Then
                Contr.TopLeftCell.Rows.EntireRow.Delete
                Contr.Delete
            End If

        Next

End Sub

2 个答案:

答案 0 :(得分:4)

而不是逐个删除行尝试类似这样的事情(未经测试):

Sub ResetForm_Click()

    Dim Contr
    Dim controlname As String
    Dim WS As Worksheet, rDel As Range

    Set WS = ActiveSheet

        For Each Contr In WS.OLEObjects

        controlname = Mid(Contr.Name, 1, 2)

            If controlname = "CB" Then
                If rDel Is Nothing then
                    Set rDel = Contr.TopLeftCell
                Else
                    Set rDel = Application.Union(rDel, Contr.TopLeftCell)
                End If 
                Contr.Delete
            End If

        Next

        If Not rDel Is Nothing then rDel.EntireRow.Delete 

End Sub

答案 1 :(得分:1)

如果没有太多编辑宏,请关闭屏幕更新和自动计算,看看是否有帮助。

在宏的开头(我通常在声明后添加),添加

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

然后在结束时(End Sub之前),将它们重新打开

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic