如何确定单元格公式是否包含常量?

时间:2013-09-27 19:04:41

标签: excel excel-vba excel-2007 excel-formula vba

在调试或质量检查工作中的Excel报告时,我发现问题是因为文本在公式中被硬编码。我听说这是一个常数和公式混合单元。

以下是我看到的例子。

常数= 100

常数= Facility

公式单元格=INDIRECT(ADDRESS(5,MATCH($A7&$B7&C$2,Data!$4:$4,0),,,$A$2))

混合单元=INDIRECT("Data!"&ADDRESS(5,MATCH($A7&$B7&C$2,Data!$4:$4,0)))

"Data!"是混合单元格中的常量,在本例中为工作表名称。如果该表名称发生了变化,则公式将会中断。我发现并使用两种条件格式来突出显示常量单元格和使用此"Identify formulas using Conditional Formatting"的公式。我需要想出一种方法来格式化公式中包含这些常量的单元格。

我有found this question并尝试使用=IF(COUNT(SEARCH(CHAR(34),A1,1)),TRUE,FALSE)FIND()来查看我是否可以检查单元格中是否有双引号,但SEARCH()返回{{1}因为它正在查看单元格值而不是它的内容。如果单元格包含FALSE,则返回TRUE但如果是公式,则返回"Constant",例如单元格包含FALSE

如何在整个工作表或工作簿中找到公式内的常量?

编辑*

感谢下面的Sidd代码,我在一个模块中创建了一个函数,我可以在条件格式中使用它来至少突出显示单元格中包含引号的单元格。

="Constant"

FormulaHasQuotes Conditional formatting pic

2 个答案:

答案 0 :(得分:1)

假设您的工作表看起来像这样。

enter image description here

这是你在尝试的吗?

Sub Sample()
    Dim ws As Worksheet
    Dim aCell As Range, FRange As Range

    '~~> Set this to the relevant sheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        '~~> Find all the cells which have formula
        On Error Resume Next
        Set FRange = .Cells.SpecialCells(xlCellTypeFormulas)
        On Error GoTo 0

        If Not FRange Is Nothing Then
            '~~> Check for " in the cell's formula
            For Each aCell In FRange
                If InStr(1, aCell.Formula, """") Then
                    Debug.Print "Cell " & aCell.Address; " has a constant"
                End If
            Next
        End If
    End With
End Sub

当您运行上面的代码时,您将获得此输出

Cell $A$2 has a constant
Cell $A$5 has a constant

注意:我已经向您展示了如何为工作表执行此操作,我相信您可以为工作簿中的所有工作表复制它吗?

答案 1 :(得分:0)

只有非常轻微的测试...

例如,不会处理包含嵌入式"

的“字符串”常量

Sub Tester()

'add reference to "Microsoft VBScript Regular Expressions 5.5"
Dim regxnum As New RegExp, regexpchar As New RegExp
Dim matches As MatchCollection, m As Match

Dim rngF As Range, c As Range

    On Error Resume Next
    Set rngF = ActiveSheet.UsedRange.SpecialCells(xlFormulas)
    On Error GoTo 0

    If Not rngF Is Nothing Then

        regxnum.Pattern = "[^A-Z$](-?\d{1,}\.?\d{0,})"
        regxnum.Global = True

        regexpchar.Pattern = "(""[^""]{0,}"")"
        regexpchar.Global = True

        For Each c In rngF.Cells
            Debug.Print c.Formula
            Set matches = regxnum.Execute(c.Formula)

            For Each m In matches
                    Debug.Print c.Parent.Name, c.Address(), m.SubMatches(0)
            Next m

            Set matches = regexpchar.Execute(c.Formula)
            For Each m In matches
                    Debug.Print c.Parent.Name, c.Address(), m.SubMatches(0)
            Next m

        Next c
    End If
End Sub
相关问题