在 Excel 中使用正则表达式,我可以在替换匹配的字符串之前对匹配的模式执行一些算术吗?
我正在使用“VBscript.RegExp”来查找和替换正则表达式。我正在尝试做这样的事情:
Dim regEx
Set regEx = CreateObject("VBScript.RegExp")
regEx.Pattern = "ID_(\d{3})"
regEx.IgnoreCase = False
regEx.Global = True
regEx.Replace(a_cell.Value, "=HYPERLINK(A" & CStr(CInt("$1") + 2) )
即我有一些包含 ID_006 之类的单元格,我想用单元格 A8 的超链接替换此类单元格的内容。因此,我匹配这三个数字,然后想在这些数字上添加 2,以获得要超链接的正确行。
但 CStr(CInt("$1") + 2)
部分不起作用。关于如何让它发挥作用有什么建议吗?
I am using `VBscript.RegExp`` to find and replace using a regular expression. I'm trying to do something like this:
Dim regEx
Set regEx = CreateObject("VBScript.RegExp")
regEx.Pattern = "ID_(\d{3})"
regEx.IgnoreCase = False
regEx.Global = True
regEx.Replace(a_cell.Value, "=HYPERLINK(A" & CStr(CInt("$1") + 2) )
I.e. I have cells which contain things like ID_006 and I want to replace the contents of such a cell with a hyperlink to cell A8. So I match the three digits, and then want to add 2 to those digits to get the correct row to hyperlink to.
But the CStr(CInt("$1") + 2)
part doesn't work. Any suggestions on how I can make it work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我已经发布了这些要点,
^
和$
匹配整个字符串。此版本运行我,您可以使用.Pattern = "ID_(\d{3})"
恢复到当前模式下面的代码在 A1:A10 运行(示例显示转储到 B1:B10 以进行前和后 coede)
Ive posted given these points
^
and$
. This version runs me, you can revert to your current pattern with.Pattern = "ID_(\d{3})"
The code below runs at A1:A10 (sample shown dumping to B1:B10 for pre and post coede)
这是因为:
"=HYPERLINK(A" & CStr(CInt("$1") + 2)
在执行代码时计算一次,而不是每次匹配都计算一次。您需要捕获& 像这样处理匹配;
或者如果它们都是 ??_NUM 格式;
This is because:
"=HYPERLINK(A" & CStr(CInt("$1") + 2)
is evaluated once, when the code is executed, not once for every match.You need to capture & process the match like this;
Or if they are all in ??_NUM format;
该行 -
不起作用,因为 VBA 会尝试对文字字符串“$1”而不是对正则表达式的匹配项执行
CInt
。如果您分两步进行替换,就会起作用,如下所示 -
The line -
won't work as VBA will try to do a
CInt
on the literal string "$1" rather than on the match from your RegEx.It would work if you did your replace in 2 steps, something like this -