Excel将文本评估为逻辑

我试图通过连接操作数和运算符来评估逻辑expression式。 在Excel 2016中是否有一个从文本转换为逻辑的公式,类似于VALUE()如何将文本转换为数字? 我正在寻找这样的解决scheme,所以我可以dynamic改变条件,而无需改变实际的Excel公式。 我已经search并阅读了Excel函数的描述,但是没有任何东西可以作为解决scheme跳出来。

 'The operands and operator A1: 1 A2: > A3: 0 'Concatenation B4: =CONCAT(A1:A3) 'This evaluates to 1>0 B5: =A1&A2&A3 'This also evaluates to 1>0 'Some checks C4: =ISTEXT(B4) 'This evaluates to TRUE. C5: =ISTEXT(B5) 'This also evaluates to TRUE D4: =ISLOGICAL(B4) 'This evaluates to FALSE D5: =ISLOGICAL(B5) 'This also evaluates to FALSE 'Vain attempts E4: =AND(B4,TRUE) 'This ALWAYS is TRUE, even when my desired output is FALSE E5: =OR(B5) 'This spits out a #VALUE! error 

由于我正在寻找dynamic的东西,我想避免一个解决scheme,如
=IF(A2=">",A1>A3,FALSE) 。 我也宁愿避免一个UDF,但是如果没有内置函数存在来转换文本中的逻辑expression式并将其评估为逻辑expression式,则愿意走这条path。

要编写一个调用Evaluate的UDF,可以处理Range或Variant / Stringinput,请尝试以下操作:

 Function L(exp As Variant) As Variant Dim vExp As Variant vExp = exp L = Application.Evaluate(vExp) End Function 

为什么它工作?

该行vExp = exp做魔术。 如果exp是一个Range,那么Assigment将使用默认的.Value属性,并将其复制为Variant / String(因为我们不使用Set )。 如果它是一个Variant / String,那么它是一个直接的副本。

它确实有使用Application.Evaluate (下面解释这里的缺点)


一个版本也处理从VBA被调用的可能性,试试

 Function L(exp As Variant) As Variant If TypeName(exp) = "Range" Then L = exp.Worksheet.Evaluate(exp.Value) Else If IsError(Application.Caller) Then 'Calls from VBA are hanbled here. ' Note: Best to fully qualify any range references in exp ' to avoid unexpected references to the active sheet L = ActiveSheet.Evaluate(exp) Else L = Application.Caller.Worksheet.Evaluate(exp) End If End If End Function 

根据没有内置函数的意见,我为逻辑创build了一个名为L()的用户自定义函数(“UDF”),取自内build函数N()和T()为数字文本

 Function L(exp As Variant) As Variant Dim limit As Integer Dim counter As Integer 'Set an upper limit to how many cycles the loop may run limit = 1000 'Assuming the possibility of nested functions, loop until the expression resolves to logical or to an error or until the loop limit has been reached Do exp = [exp] 'This avoids Error 2015 if exp is a Range reference. Comment if there's a better way! exp = Application.Evaluate(exp) 'Evaluate the expression counter = counter + 1 'Increment the loop counter Loop Until Application.IsLogical(exp) Or Application.IsError(exp) Or counter >= limit 'Return the evaluated expression L = exp End Function 

这个函数即使当我用像=L(TRUE)=L(CONCAT(A1:A2)&A3)或者甚至=l(CONCAT(A1:A2)&"""foo""")方式抛出一些愚蠢的东西, 。 但它不会抛出错误,例如=l(123)=l("123") 。 在这些情况下,谢天谢地,因为123"123"永远不会评估为逻辑或错误。