RegExp55修改大量的Excel公式

我在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)正则expression式必须是^=IF\(ISERROR\(([^)]+)\).*和replace模式应设置为=$1 (请参阅正则expression式演示 )
2)您需要使用.Replace而不是.Execute来replace公式
3)您传递的string必须是公式,更新后的string应分配给单元格公式。

正则expression式匹配:

  • ^ – string的开始
  • =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