我发现了一个宏来评估字符串。它适用于大多数公式。但这不会评估我的sumifs公式。
用于WM_Eval()的VBA如下所示:
Function wm_Eval(myFormula As String, ParamArray variablesAndValues() As
Variant) As Variant
Dim i As Long
'
' replace strings by values
'
For i = LBound(variablesAndValues) To UBound(variablesAndValues) Step 2
myFormula = RegExpReplaceWord(myFormula, variablesAndValues(i),
variablesAndValues(i + 1))
Next
'
' internationalisation
'
myFormula = Replace(myFormula, Application.ThousandsSeparator, "")
myFormula = Replace(myFormula, Application.DecimalSeparator, ".")
myFormula = Replace(myFormula,
Application.International(xlListSeparator), ",")
'
' return value
'
wm_Eval = Application.Evaluate(myFormula)
End Function
如果我输入wm_Eval(“ 1 + 1”),它就像一个超级按钮。但是如果我这样做:
="sumifs(b2:b10,a2:a10,"&D2&">=2"&D2&")" where d2=" it returns #Value.
So the formula it should evaluate would be: sumifs(b2:b10,a2:a10,">=2")
我习惯丹麦语excel-所以可能只是我很想念的非常简单的事情。
答案 0 :(得分:0)
我认为您应该提供有关为什么需要此功能的更多信息,因为我敢肯定比上述代码有更好的方法来完成任务。
该函数返回错误的原因有很多。最主要的是您的公式语法不正确。 wm_Eval()
函数需要一个公式参数,然后是变量和值参数对。您尚未包括RegExpReplaceWord()
函数的代码,但我想它会为伪公式变量运行某种形式的值替换。不看代码的那部分,很难猜测语法,但是原理的模型将是这样的:
= wm_Eval(“ SUMIFS(A1:A4,B1:B4,{a})”,“ {a}”,“> = 1”)
其中{a}被“> = 1”代替
数据类型也是一个问题,如以下语法所示:
= wm_Eval(“ SUMIFS(A1:A4,B1:B4,{a})”,“ {a}”,1)
我不想太残酷,但是这段代码的构造很差,并且无法通过各种传入的参数解析所有不同的公式。是的,它适用于SUM
,但这是因为您没有传递任何变量值对。我将避开此解决方案,并提出一些更强大的方法。例如,如果您要收集公式的字符串版本,为什么不直接传入包含公式的范围并从那里处理呢?
我可以告诉您,我已经编写了一个例程来解析公式中的值。这是一个漫长而复杂的过程,需要花费许多小时才能开发出来,其中包括一些WINAPI调用和挂钩,因此,如果您希望继续使用当前的方法,则需要做很多工作。
但是,我想我应该向您展示您当前函数的工作方式,因此我模拟了RegExpReplaceWord()
函数并注释掉了该国际化代码:
Public Function wm_Eval(myFormula As String, ParamArray variablesAndValues() As Variant) As Variant
Dim i As Long
'
' replace strings by values
'
For i = LBound(variablesAndValues) To UBound(variablesAndValues) Step 2
myFormula = RegExpReplaceWord(myFormula, variablesAndValues(i), variablesAndValues(i + 1))
Next
'
' internationalisation
'
' myFormula = Replace(myFormula, Application.ThousandsSeparator, "")
' myFormula = Replace(myFormula, Application.DecimalSeparator, ".")
' myFormula = Replace(myFormula, Application.International(xlListSeparator), ",")
'
' return value
'
wm_Eval = Application.Evaluate(myFormula)
End Function
Private Function RegExpReplaceWord(myFormula As String, variable As Variant, value As Variant) As String
If VarType(value) = vbString Then
value = """" & value & """"
End If
RegExpReplaceWord = Replace(myFormula, variable, value)
End Function
因此,在工作表单元格中,您可以添加上面引号中所示的功能。
总而言之,我不会继续使用您当前的方法,否则您将被太多错误困扰,以致丢失了 3天一无所获。