我在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