
我想創建一個自定義函數,它是 的簡寫if(somefunction(arg)=something,"sometext",somefunction(arg))
所以我不必somefunction(arg)
每次執行此操作時都重複,就像iferror
我們如何取消if(iserror(somefunction(arg)),"sometext",somefunction(arg)
例如,我希望能夠輸入iftrue(somefunction(arg),"=A1","message")
並且相當於if(sumfunction(arg)=A1,"message",sumfunction(arg))
我試過:
Function iftrue(Fx, condition, show)
iftrue = Application.WorksheetFunction.if(Fx & condition, show, Fx)
End Function
但它給了#value。
為了診斷我的問題,我嘗試了一些更簡單的函數,看看哪裡出了問題。所以我複製了 SUM 和 If 函數。
這個「求和」函數有效。
Function testsum(a, b)
test = Application.WorksheetFunction.Sum(a, b)
End Function
但這個“if”功能不起作用。
Function testif(a, b, c)
testif = Application.WorksheetFunction.if(a, b, c)
End Function
所以我認為我的問題是我調用worksheet.function.if
.
我知道我可以透過使用 VBA ifs 來解決這個問題,但這並不是我真正想要做的。
答案1
沒有Application.WorksheetFunction.If()
即使有,您仍然需要將額外的引號放入 if 的測試部分。例如,如果 fx 解析為"test"
且條件為"=test"
結果字串將是"test = test"
把那個
因此,請使用“評估”來代替。
我們需要解析特定格式的字串以進行評估。
我們需要將額外的引號推入結果字串中。例如,如果 fx 解析為"test"
且條件為 ,則"=test"
結果字串將為"test = test"
。
將其放入 Evaluate 中,函數將尋找名為 的函數test
。所以我們需要一個類似 的字串""test"="test""
,它將解析為 True。
如果條件是總是我們可以簡單地用一個平等而不是不平等IF fx = condition then
來代替一切直到並包括If tst Then
。
該函數比該函數更加動態,因為它允許不等式:
Function IFTrue(fx, condition As String, show)
Dim tst As Boolean
Dim z As Integer
Dim t As String
'test whether the condition is assuming "="
If InStr("<>=", Left(condition, 1)) = 0 Then condition = "=" & condition
'Find whether there is one or two qulifiers
If InStr("<>=", Mid(condition, 2, 1)) > 0 Then z = 2 Else z = 1
'Parse string to remove qulifiers from the quotes and make everything a string
t = """" & fx & """" & Left(condition, z) & """" & Mid(condition, z + 1) & """"
'evaluate the formula string to resolve to True or False
tst = Application.Caller.Parent.Evaluate(t)
If tst Then
IFTrue = show
Else
IFTrue = fx
End If
End Function
然後你會這樣稱呼它
=IFtrue(SUM(A1,A2),"=A3","Must Be True")
編輯
您可以使用 IIF() 並減少行數
Function IFTrue2(fx, condition As String, show)
Dim z As Integer
'test whether the condition is assuming "="
If InStr("<>=", Left(condition, 1)) = 0 Then condition = "=" & condition
'Find whether there is one or two qulifiers
If InStr("<>=", Mid(condition, 2, 1)) > 0 Then z = 2 Else z = 1
IFTrue2 = IIf(Application.Caller.Parent.Evaluate("""" & fx & """" & Left(condition, z) & """" & Mid(condition, z + 1) & """"), show, fx)
End Function