Excel中的macros – 如何replace#Value! 与在前一个单元格中的值

我有一列数字数据,但其中一些单元格包含#VALUE !. 我想replace#VALUE的单元格! 与单元格的值在同一列中,但在前一行中。 我试图macros代码,我得到一个编译器错误代码13.下面是代码。 我会感谢指向正确方向的指针。

Sub ReplaceErrorValues() ' ' ReplaceErrorValues Macro ' Macro replaces #Value! with the value of the cell in the same column and previous row ' 'Step 1: Declare variables Dim priceRange As Range Dim priceCell As Range 'Step 2: Define the Target Range Set priceRange = Range("D4:D1357") 'Step 3: Start looping through the Days range For Each priceCell In priceRange 'Step 4: Do something with every price cell If priceCell.Value = #Value! Then 'Step 5: Create a temporary variable Dim previousValue As Double priceCell.Select priceCell.Offset(-1, 0).Range("A1").Select previousValue = ActiveCell.Value priceCell.Select ActiveCell.Value = previousValue End If 'Step 6: Get the next cell in the Target range Next priceCell End Sub 

以下应该做你想做的事情在你的“步骤4”

 'Step 4: Do something with every price cell If priceCell.Value = CVErr(xlErrValue) Then priceCell.Value = priceCell.Offset(-1, 0).Value End If 

CVErr(xlErrValue)返回与Excel单元格中显示的Variant/Error值相同的值#VALUE!


如果你想检查任何错误types,不只是#VALUE! ,你可以使用

 'Step 4: Do something with every price cell If IsError(priceCell.Value) Then priceCell.Value = priceCell.Offset(-1, 0).Value End If 

IsError是一个函数,用于testing传递给它的值是否为Excel错误types( #VALUE!#N/A#DIV/0! , #NAME?等),如果是这样的值,如果不是,则为False