簡體   English   中英

Excel宏選擇包含字符串的單元格並替換字符

[英]Excel macro select cell that contains a string and replace a character

我有一個包含200多個單元格的工作表。 每個單元格包含一個公式,如下所示:

=AVERAGE('worksheetname'!range)

我想運行將公式更改為以下公式的宏:

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

我已經計算出可以將=AVERAGE更改為&AVERAGE然后搜索並用&IFERROR替換&AVERAGE 它將允許我搜索包含&IFERROR單元格,並在公式的末尾添加缺少的括號)

我想建立一個宏,但是有幾個問題:

  • 如何為每個單元格搜索和替換一次
  • 宏給我一個不匹配錯誤

下面是我的宏的代碼:

    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

您可能會發現,使用代碼“手動”進行Replace比使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM