This is an update to:
Will work for local sheet references, but not for references off-sheet. – brettdj May 14 '14 at 11:55
By Using Larrys method, just change the objRegEx.Pattern to:
(['].*?['!])?([[A-Z0-9_]+[!])?($?[A-Z]+$?(d)+(:$?[A-Z]+$?(d)+)?|$?[A-Z]+:$?[A-Z]+|($?[A-Z]+$?(d)+))
This will:
- Search for optional External links:
(['].*?['!])?
- Search for optional Sheet-reference:
([[A-Z0-9_]+[!])?
- Do the following steps in prioritized order:
- Search for ranges with row numbers (And optional $):
$?[A-Z]+$?(d)+(:$?[A-Z]+$?(d)+)?
- Search for ranges without row numbers (And optional $):
$?[A-Z]+:$?[A-Z]+
- Search for 1-cell references (And optional $):
($?[A-Z]+$?(d)+)
Resulting in this:
Sub testing()
Dim result As Object
Dim r As Range
Dim testExpression As String
Dim objRegEx As Object
Set r = Cells(1, 2) ' INPUT THE CELL HERE , e.g. RANGE("A1")
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
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
Next Match
End If
End If
End Sub
Doing this, will give you the values of all possible references, I could think of. (Updated this post, because I needed the problem solved).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…