试图清空单元格以绘制图表中的间隙

时间:2015-11-13 22:05:54

标签: excel vba excel-vba

我有一系列数据,从单元格C169:N174运行,获取折线图。单元格数据是数字或空(Excel为空) - 公式返回数字或空白文本("")。

当触发动作时,通过数据验证,我需要通过C169:C174左侧复制的最右侧单元格(N169:N174)中的公式。为此,我有这段代码:

Range("N169:N174").AutoFill Destination:=Range("C169:N174")
Range("C169:N174").Select

复制公式后,我需要清除任何包含文本("")的单元格。为此,我有这段代码:

Range("C169:M174").SpecialCells(xlCellTypeFormulas, 2).Select
Selection.ClearContents

此代码针对两组数据运行。相同的代码,不同的细胞。范围是C169:N174和C145:N150。我首先为range1(C145:N15)编写代码 - 公式复制然后删除单元格w /("")。然后对range2(C169:N174)采取相同的动作。完整代码:

Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False

If Target.Address = "$B$2" Then

'mcroCopyTrendedRentFormulas
    Range("N145:N150").AutoFill Destination:=Range("C145:N150"), Type:=xlFillDefault
    Range("C145:N150").Select

    'mcroClearTrendedRentEmptyCells
    Range("C145:N150").SpecialCells(xlCellTypeFormulas, 2).Select
    Selection.ClearContents

    'mcroCopyAskingRentFormulas
    Range("N169:N174").AutoFill Destination:=Range("C169:M174")
    Range("C169:N174").Select

    'mcroClearAskingRentEmptyCells
    Range("C169:M174").SpecialCells(xlCellTypeFormulas, 2).Select
    Selection.ClearContents

    Range("A1").Select

End If

End Sub

一旦代码被触发,如果我在工作表完成运行之前点击工作表上的任何地方,我刚刚计时并花了45秒,我得到一个错误说:

  

" 1004错误:未找到细胞"

  

" 1004错误:Range类的自动填充方法失败"。

如果我让代码运行整整45秒,它就可以了。如果我单击工作表中的任何位置并获得任何错误,请停止调试器并尝试再次运行它,我得到两个错误之一。

所以也许加速执行是个问题?

我不知道 - 在这里可以接受任何事情。

1 个答案:

答案 0 :(得分:0)

我对代码进行了轻微编辑,主要是删除多余的DllGetClassObject行(嗯,将其注释掉)并合并.Select.Select。这应该运行得快一点。请注意使用.ClearContentsScreenUpdating

Calculation

我也从Private Sub Worksheet_Change(ByVal Target As Range) If Target.Address = "$B$2" Then Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Application.EnableEvents = False 'mcroCopyTrendedRentFormulas Range("N145:N150").AutoFill Destination:=Range("C145:N150"), Type:=xlFillDefault 'Range("C145:N150").Select 'mcroClearTrendedRentEmptyCells Range("C145:N150").SpecialCells(xlCellTypeFormulas).ClearContents 'mcroCopyAskingRentFormulas Range("N169:N174").AutoFill Destination:=Range("C169:M174") 'Range("C169:N174").Select 'mcroClearAskingRentEmptyCells Range("C169:M174").SpecialCells(xlCellTypeFormulas).ClearContents Range("A1").Select End If Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic Application.EnableEvents = True End Sub 中移除了2,因为我认为不需要,并且在我删除之前也为我犯了错误。

当它正在运行时,让它运行而不点击。实际上,当任何宏在Excel中运行时,最好让它坐下来运行。