试图清空细胞来绘制图表中的空白

我有一系列数据,从单元格C169:N174运行,采购折线图。 单元格数据可以是数字,也可以是空的(Excel空) – 公式返回数字或空白文本(“”)。

当动作被触发时,通过数据validation,我需要通过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错误:未find单元格”

要么

“1004错误:范围类的自动填充方法失败”。

如果我让代码运行整个45秒,它的工作。 如果我单击工作表中的任何地方,并得到任何错误,停止debugging器,并尝试再次运行,我得到两个错误之一。

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

我不知道 – 在这里开放任何东西。

我稍微编辑了代码,主要是删除多余的。select行(好,注释掉)和合并.Select.ClearContents 。 这应该跑得快一点。 请注意使用ScreenUpdatingCalculation

 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 

我也从你的SpecialCells()移除了2 ,因为我不相信这是必需的,并且为我抛出一个错误,直到我移除它。

运行时,不要点击运行。 真的,当任何macros运行在Excel中,最好是让它坐下来运行。