突出显示包含常量公式的选区中的单元格

时间:2015-02-04 18:52:06

标签: excel vba

我正在研究excel 2007的预算。它是由其他人编写的,包含许多工作表和许多公式。我想通过创建一个输入所有/大多数常量的输入工作表来提高电子表格的效率。为了帮助完成这个过程,我希望能够突出显示包含常量的所有公式,并在我的选择中突出显示所有常量(不在公式中)。或者,如果更容易,则相反,突出显示在我的选择中不包含常量的所有公式。我主要是处理数字,而不是文本。

以下是常量的公式(=)和常量的示例:

  1. = 82000 - 50000
  2. = $ A $ 2-的 50000
  3. = A2-的 50000
  4. = F133 *** 0.05 **
  5. 50000
  6. 以下是不包含常量的公式(=)示例:

    1. = SUM(E8:P8)
    2. = $ C $ 51 *'服务细节'!$ E $ 181
    3. = K152
    4. 我能在问题中找到最接近的答案:How to determine if a cell formula contains Constants?。但我相信这篇文章特别针对在Siddharth Rout的最后评论中澄清的公式中的引文。

      非常感谢任何帮助。谢谢。 (这是我的第一篇文章,希望我的格式正确。提前道歉)

1 个答案:

答案 0 :(得分:0)

您可以使用VBA中的SPLIT函数解析公式。例如。下面的代码适用于您给出的示例。如果公式包含常量,则返回TRUE;如果公式不是公式,则返回N / A,否则返回FALSE。

可能你需要适应一点,所以它适用于所有情况,但它是一个很好的起点。

Function HasConstant(r As Range) As Variant

Application.Volatile

Dim formula As String
Dim delimiters() As String
Dim delimiter As Variant
Dim Components() As String
Dim component As Variant
Dim chars As Integer

delimiters() = Split("+ - * / = & ( ) ,")

If r.HasFormula Then

    formula = Right(r.formula, Len(r.formula) - 1)

    Do Until formula = ""

        chars = Len(formula)
        component = formula

        For Each delimiter In delimiters

            Components = Split(formula, delimiter)

            If Len(Components(0)) < chars And Len(Components(0)) > 0 Then
                component = Components(0)
                chars = Len(component)
            End If

        Next

        If IsNumeric(Replace(component, ".", Application.International(xlDecimalSeparator))) Then 'IsNumeric(component)
            HasConstant = True
            Exit Function
        ElseIf Left(CStr(component), 1) = Chr(34) And Right(CStr(component), 1) = Chr(34) Then
            HasConstant = True
            Exit Function
        End If

        If chars < Len(formula) Then
            formula = Right(formula, Len(formula) - chars - 1)
        Else
            formula = ""
        End If

    Loop

Else

    HasConstant = CVErr(xlErrNA)
    Exit Function

End If

HasConstant = False

End Function

示例:

enter image description here