替换整数值excel表

时间:2014-03-17 08:39:04

标签: excel-vba vba excel

我想要将excel中的整数7,6替换为8.但是,以下代码并没有按预期工作。它似乎是替代字符串。我使用替换功能编写了类似的代码,但即使这样也没有产生我期望的结果。我做错了什么?

Sub MacroTest()
'
Dim rng As Range, cell As Range
Set rng = Sheets("Naomi").Range("H1:H10000")

For Each cell In rng
    If cell > 0 Then
    cell = WorksheetFunction.Substitute(cell, "7,6", "8")
    End If
Next

End Sub

感谢指导我。

2 个答案:

答案 0 :(得分:1)

我猜Taosique提供了最好的方法 这就是为什么它返回String而不是Number的原因 您已经知道Substitute在WS中尝试时会返回一个字符串 尝试使用Val函数将值转换为Number,如下所示。

With Application.WorksheetFunction
    For Each cell in rng
        If cell > 0 Then
            cell = Val(.Substitute(cell, 7.6, 8))
        End If
    Next
End With

或者你也可以使用Evaluate

If cell > 0 Then
    cell = Evaluate("Value(Substitute(" & cell & ",7.6,8))")
End If

无需将7.6""括起来 Substitute接受数字作为参数。

答案 1 :(得分:0)

使用此:

If cell.Value = 7.6 Then
    cell.Value = 8
End If