【问题标题】:Excel regex match and return multiple references in formulaExcel正则表达式匹配并返回公式中的多个引用
【发布时间】: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


【解决方案1】:

这是我的最终代码

Function GrabNthreference(R As range, NthRef As Integer) As String 'based on http://stackoverflow.com/questions/13835466/find-all-used-references-in-excel-formula
Dim result As Object
Dim testExpression As String
Dim objRegEx As Object
Dim i As Integer

i = 0

Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.IgnoreCase = True
objRegEx.Global = True
objRegEx.Pattern = """.*?"""  ' remove expressions
testExpression = CStr(R.Formula)
testExpression = objRegEx.Replace(testExpression, "")
'objRegEx.Pattern = "(([A-Z])+(\d)+)"  'grab the address  think this is an old attempt so remming out
objRegEx.Pattern = "(['].*?['!])?([[A-Z0-9_]+[!])?(\$?[A-Z]+\$?(\d)+(:\$?[A-Z]+\$?(\d)+)?|\$?[A-Z]+:\$?[A-Z]+|(\$?[A-Z]+\$?(\d)+))"
If objRegEx.Test(testExpression) Then
    Set result = objRegEx.Execute(testExpression)
    If result.Count > 0 Then
        For Each Match In result
            Debug.Print Match.Value

        If i = NthRef - 1 Then
            GrabNthreference = result(i)
            Exit Function

        End If
        i = i + 1
        Next Match
    Else
    GrabNthreference = "No precedencies found"
    End If
End If

End Function

这段代码确实让我想到了使用简单的 activecell.precedences 方法,但我认为问题在于它不会报告表外,也不会指示公式是相对的还是绝对的。

欢迎任何 cmets,但我想我已经回答了我自己的问题 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多