如何在Excel中显示计算,值和变量?

时间:2016-06-29 10:06:20

标签: excel vba excel-vba worksheet-function

出于教学目的,我喜欢在Excel中执行和显示计算。要显示计算,我使用以下VBA工作表函数:

Function DisplayFormula(range_rng As Range) As String
   Application.Volatile

   If range_rng.HasArray Then
        DisplayFormula = "<-- " & " {" & range_rng.FormulaArray & "}"    
   Else
        DisplayFormula = "<-- " & " " & range_rng.FormulaArray
   End If
End Function

然而,这是有效的,我坚持执行两个修改:

  1. 我想显示在range_rng中调用的实际值。
  2. 我想显示变量而不是范围。变量将在一个单独的单元格中分配,在它们被调用的单元格旁边(见下图)。
  3. 列“C”显示DisplayFormula(B3)的(所需)输出格式:

    This is how the output should look like.

2 个答案:

答案 0 :(得分:1)

你可以尝试这种蛮力方法 我不能说这是优化的,但它可以满足你上面的两个条件。

Function DisplayFormula2(r As Range, Optional o As Variant) As String
    Dim a, b, z, x, y, w
    Dim f As String, tf As String
    Dim c As Range
    Dim i As Integer

    If IsMissing(o) Then o = 0

    a = Array("+", "-", "/", "*", "%", "&", "^", "=", _
        "<", ">", "<=", ">=", "<>", "(", ")")

    f = r.FormulaArray: tf = f
    For Each b In a
        With Application.WorksheetFunction
            tf = .Substitute(tf, b, "|")
        End With
    Next

    z = VBA.Split(tf, "|")

    For Each w In z
        Debug.Print w
        On Error Resume Next
        Set c = Range(w)
        On Error GoTo 0
        If Not c Is Nothing Then
            If IsArray(x) Then
                ReDim Preserve x(UBound(x) + 1): x(UBound(x)) = w
                ReDim Preserve y(UBound(y) + 1): y(UBound(y)) = c.Offset(0, o).Value2
            Else
                x = Array(w)
                y = Array(c.Offset(0, o).Value2)
            End If
        End If
        Set c = Nothing
    Next

    If IsArray(x) Then
        For i = LBound(x) To UBound(x)
            With Application.WorksheetFunction
                f = .Substitute(f, x(i), y(i))
            End With
        Next
    End If
    DisplayFormula2 = IIf(r.HasArray, "<-- {" & f & "}", "<-- " & f)
End Function

顺便说一句,我认为你不需要使用.Volatile所以我将其删除了。
只要将“计算”模式设置为“自动”,它就会重新计算。

C3中的实际公式:C5:
C3:=DisplayFormula(B3)
C4:=DisplayFormula2(B4)
C5:=DisplayFormula2(B5,-1)

答案 1 :(得分:0)

您可以通过将目标单元格更改为TEXT格式来实现此目的。试试这个:

Function DisplayFormula(range_rng As Range) As String
    Application.Volatile
    ActiveCell.NumberFormat = "@"

    If range_rng.HasArray Then
        DisplayFormula = "<-- " & " {" & range_rng.FormulaArray & "}"
    Else
        DisplayFormula = "<-- " & " " & range_rng.FormulaArray
    End If
End Function