根据Excel VBA中的公式创建单元格值


Answers:


3

非VBA方法:

根据详细情况命名范围

那么,C2就是 x,C3会 y 和......

要快速完成此操作:

  1. 突出显示B2:C4

  2. 在公式选项卡上单击 Create from Selection

  3. 选择 Left 然后点击确定

enter image description here

这将命名C列中突出显示的单元格;分别为x,y,z。

那么你在C6中的公式将是:

=x*y*1000/z

然后在C8:

=FORMULATEXT(C6)

enter image description here


如果这不起作用,那么以下UDF将执行您想要的操作:

Function Foo(rng As Range) As String
    Dim MathArr()
    'Add to this array as needed to find all the math functions
    MathArr = Array("*", "-", "+", "/", "(", ")")

    Dim strArr() As String
    Dim temp As String
    Dim strFormula As String
    Dim i As Long

    'Hold two versions of the formula, one manipulate and the other to use.
    strFormula = rng.Formula
    temp = rng.Formula

    'Replace all math functions with space
    For i = LBound(MathArr) To UBound(MathArr)
        strFormula = Replace(strFormula, MathArr(i), " ")
    Next i

    'Split on the space
    strArr = Split(strFormula)

    'iterate and test each part if range
    For i = LBound(strArr) To UBound(strArr)
        If test1(strArr(i)) Then
            'If range then we repace that with the value to the right of that range
            temp = Replace(temp, strArr(i), Range(strArr(i)).Offset(, -1).Value)
        End If
    Next i

    'Return text
    Foo = "=" & temp

End Function

Function test1(reference As String) As Boolean
Dim v As Range

' if the string is not a valid range it will throw and error
On Error Resume Next
Set v = Range(reference) 'try to use referenced range, is address valid?
If Err.Number > 0 Then
    Exit Function 'return false
End If
On Error GoTo 0
test1 = True
End Function

如果没有命名范围,那么C6中的公式就是 =C2*C3*1000/C4,我把它放在C8中:

=Foo(C6)

enter image description here


我没有言语要感谢你。真。万分感谢!
Ravi chawla

但是,VBA代码会给出错误,即未定义test1。
Ravi chawla

你是否在同一模块中输出了这两个功能?那里有两个?请通过单击答案的复选标记来标记为正确。
Scott Craner
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.