Excel中的宏 - 如何替换#Value!使用前一个单元格中的值

时间:2017-10-31 19:24:40

标签: excel excel-vba vba

我有一列数字数据,但有些单元格包含#VALUE!。我想替换#VALUE的单元格!与单元格的值在同一列中,但前一行。我尝试了宏代码并获得了编译器错误代码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

1 个答案:

答案 0 :(得分:2)

以下内容应该在“步骤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)返回的Variant/Error值等同于Excel单元格中#VALUE!显示的值。

如果您想检查任何错误类型,而不仅仅是#VALUE!,您可以使用

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

IsError是一个函数,用于测试传递给它的值,以查看它是否是任何Excel错误类型(#VALUE!#N/A#DIV/0!,{{如果它是这样的值,则返回#NAME?,如果不是,则返回True