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

为了教学目的,我喜欢在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. 我想显示variables,而不是范围。 variables将被分配到一个单独的单元格中,在它们被调用的单元格旁边(见下图)。

列“C”显示DisplayFormula(B3)的(所需的)输出格式:

这就是输出结果的样子。

你可以试试这个powershell方法。
我不能说这是最优化的,但它可以满足上述两个条件。

 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)

您可以通过将目标单元格更改为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