我正在使用 `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) )
IE。我有包含 ID_006 之类的单元格,我想用指向单元格 A8 的超链接替换此类单元格的内容。所以我匹配这三个数字,然后想在这些数字上加 2 以获得正确的超链接行。
但是
CStr(CInt("$1") + 2)
部分不起作用。关于如何使它工作的任何建议?
最佳答案
鉴于这些观点,我已经发布了
^
匹配整个字符串和 $
.此版本运行我,您可以使用 .Pattern = "ID_(\d{3})"
恢复到当前模式下面的代码在 A1:A10 运行(示例显示转储到 B1:B10 的前后 coede)
Sub ParseIt()
Dim rng1 As Range
Dim rng2 As Range
Dim regEx
Set rng1 = Range([a1], [a10])
Set regEx = CreateObject("VBScript.RegExp")
With regEx
'match entire string
.Pattern = "^ID_(\d{3})$"
'match anywhere
' .Pattern = "ID_(\d{3})"
.IgnoreCase = False
For Each rng2 In rng1
If .test(rng2.Value) Then
'use Anchor:=rng2.Offset(0, 1) to dump one column to the right)
ActiveSheet.Hyperlinks.Add Anchor:=rng2, Address:="", SubAddress:= _
Cells(.Replace(rng2.Value, "$1") + 2, rng2.Column).Address, TextToDisplay:=Cells(.Replace(rng2.Value, "$1") + 2, rng2.Column).Address
End If
Next
End With
End Sub
关于regex - 在 Excel 中使用正则表达式,我可以在替换匹配的字符串之前对匹配的模式执行一些算术运算吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7687573/