简体   繁体   English

使用IIf语法错误

[英]Syntax error using IIf

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,并希望在某些情况下实现它以节省几行。

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. 我已经扫描了MSDN这篇文章,所以我不是在这里偷懒。

That's not how the IIf function works. 这不是IIf功能的工作原理。

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: 乍一看, IIf工作方式有点像三元运算符在其他语言中的作用:

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

Condition, value if true, value if false, and both possible values are of the same type. 条件,值(如果为true),值(如果为false),并且两个可能的值属于同一类型。

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. 不过要小心, IIf计算所有两个 的部分,所以你不会希望有副作用出现。 For example, calling the below Foo procedure: 例如,调用以下Foo过程:

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. 这就是为什么使用IIf控制流量并不理想。 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. 但是当真实结果错误结果参数是常量表达式时 ,如果明智地使用它,它可以通过将If...Else...End If块转换为简单的函数调用来帮助提高代码的可读性。

Like all good things, best not abuse it. 像所有好东西一样,最好不要滥用它。

You cannot use iif like this. 你不能像这样使用iif

Here is a possible way to solve this: 这是解决此问题的可能方法:

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

IIf returns a value. IIf返回一个值。 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. 正如Mat's Mug所说,您可以使用它来将数据传递到另一个方法或函数,但是您不能调用没有返回值的过程或函数。 IsNumeric() for the conditional is okay, though. 但条件的IsNumeric()是可以的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM