我正在使用`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)
部分不起作用。关于如何使其发挥作用的任何建议?
答案 0 :(得分:1)
这是因为:"=HYPERLINK(A" & CStr(CInt("$1") + 2)
在代码执行时评估一次,而不是每次匹配一次。
你需要捕获&像这样处理比赛;
a_cell_Value = "*ID_006*"
Set matches = regEx.Execute(a_cell_Value)
Debug.Print "=HYPERLINK(A" & CLng(matches(0).SubMatches(0)) + 2 & ")"
>> =HYPERLINK(A8)
或者如果它们都是?? _ NUM格式;
a_cell_Value = "ID_11"
?"=HYPERLINK(A" & (2 + val(mid$(a_cell_Value, instr(a_cell_Value,"_") +1))) & ")"
=HYPERLINK(A13)
答案 1 :(得分:1)
我发布了这些要点
^
和$
匹配整个字符串。此版本运行我,您可以使用.Pattern = "ID_(\d{3})"
下面的代码在A1:A10运行(示例显示转储到B1:B10,用于前后同步)
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
答案 2 :(得分:0)
行 -
regEx.Replace(a_cell.Value, "=HYPERLINK(A" & CStr(CInt("$1") + 2) )
不会工作,因为VBA会尝试在文字字符串上执行CInt
" $ 1"而不是你的RegEx的比赛。
如果您通过两个步骤完成替换,那将会有效 -
Dim a_cell
a_cell = Sheets(1).Cells(1, 1)
Dim regEx
Set regEx = CreateObject("VBScript.RegExp")
regEx.Pattern = "ID_(\d{3})"
regEx.IgnoreCase = False
regEx.Global = True
a_cell = regEx.Replace(a_cell, "$1")
Sheets(1).Cells(1, 1) = "=HYPERLINK(A" & CStr(CInt(a_cell) + 2) & ")"