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
- VBA正则expression式匹配时间范围,如“1:30 pm – 12:00 am”
- Excel VBA正则expression式匹配位置
- macros中没有任何东西会使Excel 2013崩溃
- 正则expression式来确定一个string是一个范围的名称还是一个单元格的地址
- 如何通过函数或自定义函数获得excel中的正则expression式支持?
- C ++ Excel :: RangePtr – expression式必须是一个指向完整对象types的指针
- 在Excel或R中匹配通配符数组
- Excel的正则expression式,或导出到Python? ; Python中的“Vlookup”?
- 想要replace工作簿中的某些单元格。 Excel是否支持search和replace中的正则expression式?