找不到为什么我的VBA简单正则expression式命令不起作用
在Excel VBA中使用此行时:
Cells(a, 20).Value = regexProjet.Execute(Cells(a, 1).Value)(0)
我得到一个警告,说参数或命令是无效的。
我在我的代码中的许多地方使用这一行,它工作得很好,单元格的格式都是标准的(他们是string…)。
任何人都可以给我一些什么样的线索?
仅供参考这是我如何宣布正则expression式:
Dim regexProjet As Object Set regexProjet = CreateObject("VBScript.RegExp") regexProjet.IgnoreCase = True regexProjet.Pattern = "^ ([az]+)(-)([0-9]+)" 'conserve seulement la clé du projet
如果你的正则expression式不符合你的数据,你会得到这个回应。 为了避免它,使用你正在使用的技术,首先做一个testing,看看你的正则expression式匹配你的string。
例如:
If regexProjet.test(Cells(a,1).value) then Cells(a, 20).Value = regexProjet.Execute(Cells(a, 1).Value)(0) Else ... your error routine End If
此外,你应该注意,如果你只是想匹配整体模式,不需要捕获组(他们将增加执行时间,使正则expression式效率较低)。
这里是我在Excel 2013中运行的示例代码,但它与您所拥有的略有不同。 我从[如何正则expression式]得到了代码: http : //support.microsoft.com/kb/818802
Sub testreg() Dim regexProjet As New RegExp Dim objMatch As Match Dim colMatches As MatchCollection Dim RetStr As String RetStr = "" regexProjet.IgnoreCase = True regexProjet.Pattern = "^ ([az]+)(-)([0-9]+)" Set colMatches = regexProjet.Execute(Cells(1, 1).Value) For Each objMatch In colMatches ' Iterate Matches collection. RetStr = RetStr & " " & objMatch.Value Next Cells(1, 20).Value = RetStr End Sub