【发布时间】:2017-04-27 23:18:40
【问题描述】:
我需要一些代码来测试一个单元格是否包含一个引用另一个单元格的公式。
我找到了答案Find all used references in Excel formula,但解决方案也错误地匹配了引用表格列的公式:
=SearchValInCol2(Tabella1[articolo];[@articolo];Tabella1[b])
然后,我使用 Like 运算符编写了以下 VBA 代码,但使用正则表达式的解决方案肯定会更可靠(我认为以下代码在许多情况下都不起作用)。
Private Function TestIfCellContainsAFormula(cellToTest As Variant) As Boolean
Dim result As Object
Dim r As Range
Dim testExpression As String
Dim objRegEx As Object
Set r = cellToTest ' 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.FormulaR1C1)
' search for pattern "=R[-3]C+4"
If testExpression Like "*R[[]*[]]*C*" Then
TestIfCellContainsAFormula2 = True
Exit Function
End If
' search for pattern "=RC[2]"
If testExpression Like "*R*C[[]*[]]*" Then
'If InStr(1, testExpression, "C[", vbTextCompare) <> 0 Then
TestIfCellContainsAFormula2 = True
Exit Function
End If
TestIfCellContainsAFormula2 = False
End Function
【问题讨论】:
-
这就是你要找的东西吗?