下面是在 Excel 中设置的示例,
[column1] [column2]
A1 =C3-C5
A2 =((C4-C6)/C6)
A3 =C4*C3
A4 =C6/C7
A5 =C6*C4*C3
我需要提取公式中使用的引用
例如,
for "A1", I simply need to get the C3 and C5.
for A2, I need to get the C4 and C6.
最佳答案
这是对以下内容的更新:
Will work for local sheet references, but not for references off-sheet. – brettdj May 14 '14 at 11:55
通过使用 Larrys 方法,只需将 objRegEx.Pattern 更改为:
(['].*?['!])?([[A-Z0-9_]+[!])?(\$?[A-Z]+\$?(\d)+(:\$?[A-Z]+\$?(\d)+)?|\$?[A-Z]+:\$?[A-Z]+|(\$?[A-Z]+\$?(\d)+))
这将:
- 搜索可选的外部链接:
(['].*?['!])?
- 搜索可选的工作表引用:
([[A-Z0-9_]+[!])?
- 按优先顺序执行以下步骤:
- 搜索包含行号的范围(以及可选的 $):
\$?[A-Z]+\$?(\d)+(:\$?[A-Z]+\$?(\d)+ )?
- 搜索不带行号的范围(以及可选的 $):
\$?[A-Z]+:\$?[A-Z]+
- 搜索 1 单元格引用(以及可选的 $):
(\$?[A-Z]+\$?(\d)+)
结果是:
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
这样做,将为您提供我能想到的所有可能引用的值。 (更新了这篇文章,因为我需要解决问题)。
关于vba - 查找Excel公式中所有使用的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13835466/