Excel VBA如何替换包含大于零的数字的每个单元格

时间:2013-09-20 16:41:39

标签: excel excel-vba vba

如何在范围内替换大于零的数字?

我可以替换给定范围内的一个特定单词或数字:

Sheet1.Columns("N").Replace What:="1", Replacement:="Good", LookAt:=xlWhole, 
  SearchOrder:=xlByRows, MatchCase:=False

现在,如果我想替换包含大于零的数字的所有内容,如1-1000000,如果我使用循环语句,将使宏运行缓慢。

我希望可以有一个代码:

Sheet1.Columns("N").Replace What:=">0", Replacement:="Good", LookAt:=xlWhole,
  SearchOrder:=xlByRows, MatchCase:=False`

3 个答案:

答案 0 :(得分:3)

您可以使用过滤器:

Sub tgr()

    On Error Resume Next    'Prevents error if there are no cells with value >0
    With Intersect(Sheet1.UsedRange, Sheet1.Columns("N"))
        .AutoFilter 1, ">0"
        .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible).Value = "Good"
        .AutoFilter
    End With
    On Error GoTo 0         'Remove the On Error Resume Next condition

End Sub

答案 1 :(得分:0)

您可以使用= EVALUATE(),但以下内容不应太慢:

Sub qwerty()
    Dim r As Range, rFix As Range, rr As Range
    Set r = Intersect(ActiveSheet.UsedRange, Range("N:N"))
    Set rFix = Nothing
    For Each rr In r
        If IsNumeric(rr.Value) Then
            If rr.Value > 0 Then
                If rFix Is Nothing Then
                    Set rFix = rr
                Else
                    Set rFix = Union(rr, rFix)
                End If
            End If
        End If
    Next
    rFix.Value = "Good"
End Sub

答案 2 :(得分:0)

尝试:

Sub PositiveIsGood()
For x = 1 To ActiveSheet.UsedRange.Rows.Count
    If Cells(x, "N") > 0 Then
        Cells(x, "N") = "Good"
    End If
Next x

End Sub