简体   繁体   English

找不到为什么我的VBA简单正则表达式命令不起作用

[英]Cannot find why my VBA simple regex command isn't working

When using this line in Excel VBA: 在Excel VBA中使用此行时:

Cells(a, 20).Value = regexProjet.Execute(Cells(a, 1).Value)(0)

I get a warning saying that either the parameter or the command is invalid. 我收到一条警告,指出参数或命令无效。

I have use this line in many places in my code and it worked fine, the format of the cells are all standard (they're strings...). 我在代码中的很多地方都使用了这一行,并且运行良好,单元格的格式都是标准的(它们是字符串...)。

Anyone could give me some hints of what to look for? 任何人都可以给我一些寻找的提示吗?

FYI this is how I declared the regex: 仅供参考,这就是我声明正则表达式的方式:

Dim regexProjet As Object
Set regexProjet = CreateObject("VBScript.RegExp")
regexProjet.IgnoreCase = True
regexProjet.Pattern = "^   ([a-z]+)(-)([0-9]+)" 'conserve seulement la clé du projet

You will get that response if your regex does not match your data. 如果您的正则表达式与您的数据不匹配,您将得到该响应。 To avoid it, using the technique you are using, first do a test to see if your regex matches your string. 为了避免这种情况,请使用您正在使用的技术,首先进行测试以查看您的正则表达式是否与您的字符串匹配。

eg: 例如:

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

Also, you should note that if you are just trying to match the overall pattern, there is no need for the capturing groups (and they will add execution time, making the regex less efficient). 另外,您应该注意,如果您只是想匹配整体模式,则不需要捕获组(捕获组会增加执行时间,从而使正则表达式的效率降低)。

Here is sample code I got to run in Excel 2013 but it's slightly different than what you have. 这是我必须在Excel 2013中运行的示例代码,但与您所拥有的略有不同。 I got the code from [How to regular expressions]: http://support.microsoft.com/kb/818802 我从[如何使用正则表达式]中获取了代码: 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 = "^   ([a-z]+)(-)([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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM