RegExp55修改了大量的Excel公式

时间:2017-03-09 08:29:07

标签: regex excel vba excel-formula

我在Excel中有以下电子表格:

+---+----+-----------------------------+----------------------------+
|   | A  |              B              |             C              |
+---+----+-----------------------------+----------------------------+
| 1 |    |                             |                            |
| 2 | 12 | =IF(ISERROR(A2/0),"",A2/0)  | =IF(ISERROR(A2*4),"",A2*4) |
+---+----+-----------------------------+----------------------------+

我希望得到以下内容

+---+----+--------+-------+
|   | A  |   B    |   C   |
+---+----+--------+-------+
| 1 |    |        |       |
| 2 | 12 | =A2/0  | =A2*4 |
+---+----+--------+-------+

所以我写了这个VBA代码:

Sub DeleteIfError()


    Dim c As Integer
    Dim r As Integer
    Dim regex As Object, str As String
    Set regex = CreateObject("VBScript.RegExp")

    With regex
    .Pattern = "=IF(ISERROR\([A-Za-z0-9]+\)"
    .Global = False 'Only First
    End With

For c = 1 To 3
    For r = 1 To 2
        If Cells(r, c).HasFormula Then

            Set matches = regex.Execute(str)
                For Each Match In matches
                    Cells(r, c) = Match.Value
                Next Match
        End If

    Next r
Next c

End Sub

但它给我一个运行时错误5020。 我认为问题在于模式,但我真的无法理解如何解决它。有人可以帮我吗?

1 个答案:

答案 0 :(得分:4)

您可以使用以下修复:

1)正则表达式必须为^=IF\(ISERROR\(([^)]+)\).*,替换模式应设为=$1(请参阅the regex demo
 2)您需要使用.Replace而不是.Execute来替换公式
 3)您传递的字符串必须是公式,更新的字符串应分配给单元格公式。

正则表达式匹配:

  • ^ - 字符串开头
  • =IF\(ISERROR\( - 文字字符序列=IF(ISERROR(
  • ([^)]+) - 捕获第1组(稍后提及$1)匹配除)以外的1个字符
  • \) - 文字)
  • .* - 其余部分一直到最后

代码:

Sub DeleteIfError()
    Dim c As Integer
    Dim r As Integer
    Dim regex As Object, str As String
    Set regex = CreateObject("VBScript.RegExp")

    With regex
    .pattern = "^=IF\(ISERROR\(([^)]+)\).*"
    .Global = False 'Only First
    End With

For c = 1 To 3
    For r = 1 To 2
        If Cells(r, c).HasFormula Then
             Cells(r, c).Formula = regex.Replace(Cells(r, c).Formula, "=$1")
        End If

    Next r
Next c

End Sub