如何从Excel中的if语句中提取'logical_test'?

我正在制定一个excel电子表格进行计算,我需要能够显示公式与决定,大部分是非常简单的,但是当我在excel单元格中find'if'公式时,我不想显示value_if_true和value_if_false …只是logical_test值。

例:

公式为: =if(and(5<=A1, A1<=10),"Pass", "Fail");

结果将是: "and(5<=A1, A1<=10)"

我需要能够处理复杂的逻辑testing,这些testing可能包含嵌套的if语句,所以只是在逗号分割将无法可靠地工作。 同样,value_if_true和value_if_false语句也可以包含if语句。

有任何想法吗?

如果对你要求的有清楚的理解,那么你可以使用类似的东西(只能和IF()语句一起使用:

 Function extrIf(ByVal ifstatement As Range) As String Dim S$, sRev$, x%, k S = Replace(Replace(ifstatement.Formula, "IF(", "\"), "),", ")|") sRev = StrReverse(S) If InStr(1, sRev, "|") > InStr(1, sRev, "\") Or InStr(1, sRev, "|") = 0 Then x = InStr(1, StrReverse(Left(sRev, InStr(1, sRev, "\"))), ",") - 1 S = Mid(S, 1, Len(S) - InStr(1, sRev, "\") + x) & "|" End If sRev = "" For Each k In Split(S, "|") If k <> "" Then If k Like "*\*" Then sRev = sRev & ", " & Mid(k, InStr(1, k, "\") + 1, 999) End If End If Next extrIf = Mid(sRev, 3, 999) End Function 

例:

在这里输入图像说明

testing:

在这里输入图像描述

也许这不是对你的完整解决scheme,但我认为这可能会给你正确的方向。

如果单元格公式以If语句开始,那么可以通过确定第一个逗号的位置(前一个左括号之和 – 先前的和号= 0)来返回逻辑testing(从第一个左括号开始)。

公式

在这里输入图像描述

 Function ExtractIfTest(Target As Range) As String Dim ch As String, s As String Dim openP As Long Dim x As Long s = Target.formula For x = 5 To Len(s) ch = Mid(s, x, 1) If Mid(s, x, 1) = "(" Then openP = openP + 1 ElseIf Mid(s, x, 1) = ")" Then openP = openP - 1 ElseIf Mid(s, x, 1) = "," And openP = 0 Then ExtractIfTest = Mid(s, 5, x - 12) End If Next End Function 

结果

在这里输入图像描述

有可能是逗号没有括号A1,B1 。 如果发生这种情况,用圆括号(A1,B1)

我写了一个UDF,提取目标公式的任何参数。 它接近托马斯答案中的那个,但是更加全球化并且考虑了可以包含逗号或括号的string。

 Function ExtractFormulaParameter(Target As Range, Optional Position As Long = 1) As Variant Dim inString As Boolean Dim formula As String Dim st As Long, sp As Long, i As Long, c As String Dim parenthesis As Long, comma As Long formula = Target.formula st = 0: sp = 0 If Position <= 0 Then ExtractFormulaParameter = CVErr(xlErrValue): Exit Function For i = 1 To Len(formula) c = Mid$(formula, i, 1) If inString Then If c = """" Then inString = False End If Else Select Case c Case """" inString = True Case "(" parenthesis = parenthesis + 1 If parenthesis = 1 And Position = 1 Then st = i + 1 End If Case ")" parenthesis = parenthesis - 1 If parenthesis = 0 And sp = 0 Then sp = i: Exit For Case "," If parenthesis = 1 Then comma = comma + 1 If Position = 1 And comma = 1 Then sp = i: Exit For If Position > 1 And comma = Position - 1 Then st = i + 1 If Position > 1 And comma = Position Then sp = i: Exit For End If Case Else End Select End If Next i If st = 0 Or sp = 0 Then ExtractFormulaParameter = CVErr(xlErrNA) Else ExtractFormulaParameter = Mid$(formula, st, sp - st) End If End Function 

默认情况下,它返回第一个参数,但是你也可以返回第二个或第三个参数,它应该适用于任何公式。

感谢所有答复。 我想到了这一点,并最终提出了类似的解决scheme,以上发布的 – 基本上是string操作来提取文本,我们期望find逻辑testing。

工作得不错,我相信我可以用它从子串中提取更多的逻辑testing。