我在Excel电子表格如下:RegExp55修改大量的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. 我认为问题是在模式,但我重新盟友无法理解如何解决它。任何人都可以帮助我吗?
看来你错过了逃跑的第一个左括号? –
你在哪里给'str'赋值? –
@WiktorStribiżew是对的,你似乎错过了最重要的部分:'str = Cells(r,c).Formula'在执行你的正则表达式之前!然后,它应该是:'Cells(r,c).Formula = Match.Value'(因为在模式中有'=',所以只有一个匹配,所以循环不是很有用) – R3uK