EXCEL如何让计算式内数值都乘以一个系数,显示新计算式的函数,以此类推?
针对这个用一个自定义函数解决;
真是第二次更新版,适应各种复杂公式的情况。
在工作表中,按Alt+F11进入VBE窗口,依次按Alt、i、m插入一个模块,将代码复制进行进去,关闭VBE界面回到excel。
可按照公式输入,修改你的算式,并提供也给直接计算结果的函数
比如:
b1=FormulaModify(A1,1.3)
c1=GetFormulaResult(A1)
代码如下:
Option Explicit
Function GetFormulaResult(ByVal 算式 As Variant) As Double
GetFormulaResult = Application.Evaluate("=" & 算式)
End Function
Function FormulaModify(ByVal 算式 As Variant, ByVal 系数 As Double) As String
Dim arr, brr As Variant
Dim i, k As Long
Dim x, result As String
arr = SplitNull(算式)
'MsgBox Join(arr, "")
ReDim brr(1 To UBound(arr))
k = 1: i = 1
For i = 1 To UBound(arr)
If VBA.IsNumeric(arr(i)) Or Asc(arr(i)) = 46 Then
Else
brr(k) = i: k = k + 1
End If
Next
ReDim Preserve brr(1 To k - 1)
'MsgBox Join(brr, "/")
For i = 1 To UBound(brr)
If i = 1 Then
If brr(i) = 1 Then
result = arr(i)
Else
x = CDbl(Mid(算式, 1, brr(i) - 1)) * 系数
result = IIf(x Like ".*", Application.Text(0 & x, "@"), x) & arr(brr(i))
End If
Else
If brr(i) - brr(i - 1) = 1 Then
x = ""
Else
x = CDbl(Mid(算式, brr(i - 1) + 1, brr(i) - brr(i - 1) - 1)) * 系数
End If
result = result & IIf(x Like ".*", Application.Text(0 & x, "@"), x) & arr(brr(i))
End If
Next
If brr(i - 1) <> Len(算式) Then
x = CDbl(Mid(算式, brr(i - 1) + 1, Len(算式) - brr(i - 1))) * 系数
result = result & IIf(x Like ".*", Application.Text(0 & x, "@"), x)
End If
FormulaModify = result
End Function
Function SplitNull(ByVal SourceString As String) As Variant
Dim i, arr() As Variant
ReDim arr(1 To Len(SourceString))
For i = 1 To Len(SourceString)
arr(i) = VBA.Mid(SourceString, i, 1)
Next
SplitNull = arr()
End Function
这个公式只针对单一运算符有效,多种类型复杂运算,处理起来相对比较复杂,还要花点精力进一步优化,暂时没有更好的思路。
我有思路了再给你持续优化。
原先的计算式内的数值都乘以系数2,然后显示新的计算式。您说的是出结果,我要的还是新的计算式。这样说可以理解我的意思了吗?