我正在整理一个excel电子表格用于计算,我需要能够显示公式以便做出决定,因为大多数情况下它非常直接,但是当我来到'if'公式时一个excel单元格,我不想显示value_if_true和value_if_false ...只是logical_test值。
示例:
公式为:=if(and(5<=A1, A1<=10),"Pass", "Fail");
结果将是:"and(5<=A1, A1<=10)"
我需要能够使用复杂的逻辑测试,其中可能包含嵌套的if语句,因此只需在逗号中拆分就无法可靠地工作。类似地,value_if_true和value_if_false语句也可以包含if语句。
有什么想法吗?
答案 0 :(得分:2)
如果对你的要求有清楚的了解,那么你可以使用这样的东西(只能用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
示例:
试验:
也许这不是完整的解决方案,但我认为它可能会给你正确的方向。
答案 1 :(得分:1)
如果单元格公式以If
语句开头,则可以通过确定第一个逗号的位置来返回逻辑测试(从第一个左括号开始),其中前一个左括号的总和 - 总和前一个关闭= 0。
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)
答案 2 :(得分:0)
我编写了一个UDF,它提取了目标公式的任何参数。它与托马斯答案中的答案很接近,但更全局并且考虑了可以用逗号或括号括起来的字符串。
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
默认情况下,它返回第一个参数,但您也可以返回第二个或第三个参数,它应该适用于任何公式。
答案 3 :(得分:0)
感谢所有回复。我更多地考虑了这一点,最后提出了类似于上面发布的解决方案 - 基本上是字符串操作来提取我们期望找到逻辑测试的文本。
运行良好,我确信我也可以用它从子串中提取更多的逻辑测试。