Syntax error using IIf

僤鯓⒐⒋嵵緔 提交于 2019-12-14 02:08:03

问题


This is a simple question I hope. I learned about IIf today and want to implement it in some cases to save a few lines.

IIF(isnumeric(inputs), resume next, call notnum)

This is in red meaning there is a syntax error, how fix this? I have scanned MSDN article on this so I am not being lazy here.


回答1:


That's not how the IIf function works.

It's a function, not a statement: you use its return value like you would with any other function - using it for control flow is a bad idea.

At a glance, IIf works a little bit like the ternary operator does in other languages:

string result = (foo == 0 ? "Zero" : "NonZero");

Condition, value if true, value if false, and both possible values are of the same type.

It's for turning this:

If foo = 0
    Debug.Print "Zero"
Else
    Debug.Print "NonZero"
End If

Into this:

Debug.Print IIf(foo = 0, "Zero", "NonZero")

Be careful though, IIf evaluates both the true and the false parts, so you will not want to have side-effects there. For example, calling the below Foo procedure:

Public Sub Foo()
    Debug.Print IIf(IsNumeric(42), A, B)
End Sub

Private Function A() As String
    Debug.Print "in A"
    A = "A"
End Function

Private Function B() As String
    Debug.Print "in B"
    B = "B"
End Function

Results in this output:

in A
in B
A

That's why using IIf for control flow isn't ideal. But when the true result and false result arguments are constant expressions, if used judiciously, it can help improve your code's readability by turning If...Else...End If blocks into a simple function call.

Like all good things, best not abuse it.




回答2:


You cannot use iif like this.

Here is a possible way to solve this:

if isnumeric(input) then
    do something ...
else
    call notnum
end if



回答3:


IIf returns a value. As Mat's Mug stated, you can use it, to hand data into another method or function, but you can't call a procedure or function, which has no return value. IsNumeric() for the conditional is okay, though.



来源:https://stackoverflow.com/questions/34211344/syntax-error-using-iif

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!