Excel macro select cell that contains a string and replace a character

时间:2015-07-13 21:01:39

标签: string vba excel-vba replace find

I have a worksheet with more than 200 cells. Each cell contains a formula as below:

=AVERAGE('worksheetname'!range)

I want to run a macro that changes the formula to following formula:

=IFERROR(AVERAGE('worksheetname'!range),100%)

I have worked out that I can change =AVERAGE into for example &AVERAGE and than search & replace &AVERAGE with &IFERROR. It will allow me to search for cells which contains &IFERROR and add missing parenthesis at the end of formula )

I want to build a macro but have few problems:

  • how to search & replace it all once for each cell
  • macro gives me a mismatch error

below is a code for my macro:

    Sub aaaa()

'
' IFERROR Macro
'

'
    Dim myRange As Range
    Dim myCell As Range
    Dim i As Integer
    Set myRange = Range("E4:BB120")


    Sheets("Zones").Select

    Cells.Replace What:="=AVERAGE(", Replacement:="&IFERROR(AVERAGE(", LookAt _
        :=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False

    For Each myCell In myRange
    If myCell Like "*&IFERROR*" Then
    myCell.Select

    i = 1
    Do While i < 2
    Selection.Replace What:=")", Replacement:="),100%)", LookAt _
        :=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
    i = i + 1
    Loop
    End If
    Next myCell

    Cells.Replace What:="&IFERROR(AVERAGE(", Replacement:="=IFERROR(AVERAGE(", LookAt _
        :=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False





End Sub

1 个答案:

答案 0 :(得分:2)

您可能会发现更换更容易&#34;手动&#34;在代码中而不是使用Replace

Sub aaaa()


    Dim myRange As Range
    Dim c As Range
    Dim f As String, i As Long


    On Error Resume Next
    Set myRange = Sheets("Zones").Range("E4:BB120").SpecialCells( _
                                                xlCellTypeFormulas)
    On Error GoTo haveError

    If myRange Is Nothing Then Exit Sub

    Application.Calculation = xlCalculationManual

    For Each c In myRange.Cells
        f = c.Formula
        If f Like "=AVERAGE(*)" Then
            c.Formula = "=IFERROR(" & Right(f, Len(f) - 1) & ",100%)"
            i = i + 1
        End If
    Next c

    MsgBox "Replaced " & i & " formulas"

haveError:

    If Err.Number <> 0 Then MsgBox Err.Description
    Application.Calculation = xlCalculationManual
End Sub