vba - 查找Excel公式中所有使用的引用

标签 vba excel

下面是在 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)+))

这将:

  1. 搜索可选的外部链接:(['].*?['!])?
  2. 搜索可选的工作表引用:([[A-Z0-9_]+[!])?
  3. 按优先顺序执行以下步骤:
  4. 搜索包含行号的范围(以及可选的 $):\$?[A-Z]+\$?(\d)+(:\$?[A-Z]+\$?(\d)+ )?
  5. 搜索不带行号的范围(以及可选的 $):\$?[A-Z]+:\$?[A-Z]+
  6. 搜索 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/

相关文章:

sorting - Excel VBA 按特定列对命名范围进行排序

python - Pandas read_excel : nan values forcing others in the same column to be converted to float

excel - 为 Excel VBA 解决方案创建用户帮助文档的最佳方法是什么?

excel - 当单元格打开并选择另一个工作表时,Workbook_sheetChange 崩溃

excel - 插入行时防止公式引用更新

mysql - Excel 2016 - 在 b 列中查找匹配行,然后对 C 列求和,将总和复制到下一个工作表 A 列中

java - apache.poi HSSFCell getNumericCellValue 读取不正确

excel - 是否可以根据条件制作数字序列?

r - openxlsx : read. 如果工作表名称包含 "&"字符,xlsx 会引发错误

excel - 转换为日期