【发布时间】:2016-10-21 08:38:28
【问题描述】:
我创建了一个函数,该函数将返回包含工作表名称(如果存在)的第 N 个引用,但它不适用于所有实例。我正在使用的正则表达式字符串是
'[\w ]+[']!([$]{0,1})([A-Z]{1,2})([$]{0,1})(\d{1,5})
我发现它在以下任何一个示例中都找不到第一个引用:
='Biscuits Raw Data'!G783/'Biscuits Raw Data'!E783
=IF('Biscuits Raw Data'!G705="","",'Biscuits Raw Data'!G723/'Biscuits Raw Data'!G7005*100)
以下是我的功能代码:
Function GrabNthreference(Rng As range, NthRef As Integer) As String
Dim patrn As String
Dim RegX
Dim Matchs
Dim RegEx
Dim FinalMatch
Dim Subm
Dim i As Integer
Dim StrRef As String
patrn = "'[\w ]+[']!([$]{0,1})([A-Z]{1,2})([$]{0,1})(\d{1,5})"
StrRef = Rng.Formula
Set RegEx = CreateObject("vbscript.regexp") ' Create regular expression.
RegEx.Global = True
RegEx.Pattern = patrn ' Set pattern.
RegEx.IgnoreCase = True ' Make case insensitive.
Set RegX = RegEx.Execute(StrRef)
If RegX.Count < NthRef Then
GrabNthreference = StrRef
Exit Function
End If
i= -1
For Each Matchs In RegX ' Iterate Matches collection.
Set Subm = RegX(i).submatches
i = i + 1
If i = NthRef -1 Then
GrabNthreference = RegX(i)
Exit Function
End If
'Debug.Print RegX(i)
Next
结束函数
【问题讨论】:
-
啊哈!发现一些不同的代码让我意识到我的错误,即 i = i+1 在 i=0 时报告 RegX(i) 之前递增到 1。我将废弃上面的代码并使用以下代码。感谢@michael-møldrup 提供他的代码。 link
标签: regex excel reference excel-formula match