IFERROR と同じように動作する IFTRUE という関数を作成しますが、関数は TRUE を返します。Worsheetfunction.if は機能しません。何が間違っているのでしょうか?

IFERROR と同じように動作する IFTRUE という関数を作成しますが、関数は TRUE を返します。Worsheetfunction.if は機能しません。何が間違っているのでしょうか?

私は、カスタム関数を作成して、これを実行する際に毎回if(somefunction(arg)=something,"sometext",somefunction(arg))同じことを繰り返さなくても済むようにしたいと考えていました。somefunction(arg)iferrorif(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

しかし、それは#価値を与えます。


問題を診断するために、いくつかのより単純な関数を試して、どこが間違っているのかを確認しました。そこで、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 if を使用することでこれを回避できることはわかっていますが、それは私が本当にやりたいことではありません。

答え1

ありませんApplication.WorksheetFunction.If()

たとえあったとしても、ifのテスト部分に余分な引用符を挿入する必要があります。たとえば、fxが"test"and条件に解決された場合"=test"、結果の文字列は次のようになります。"test = test"

それを置く

代わりに Evaluate を使用してください。

評価するには、特定の形式で文字列を解析する必要があります。

結果の文字列に追加の引用符を挿入する必要があります。たとえば、fx が に解決され"test"、条件が だった場合"=test"、結果の文字列は になります"test = test"

これを Eva​​luate に入れると、関数は という名前の関数を探します。したがって、 True に解決される のようtestな文字列が必要です。""test"="test""

もしその状態がいつもは等式であり、決して不等式ではありません。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

関連情報