Excel VBA内联IF语句使变量0

时间:2015-10-13 15:44:45

标签: excel vba excel-vba inline-if

我正在尝试减少If ... Then ... Else语句中的代码量,并尝试使用IIf(表达式,true,false)来设置变量。我有一个问题,不知何故变量设置为0并且它非常烦人。

例如:

'Declarations for testing (changing currenty to work for bot and top)
xval = 15
currenty = 20

largebot = 5
largecen = 5
largetop = 5

这个有效:

largebot = IIf(xval > largebot, IIf(currenty >= -1 And currenty <= 21, xval, largebot), largebot)

但是这个没有:

largetop = IIf(xval > largetop, IIf(Range("B2").Value = "RED or BLUE", IIf(material = 18, IIf(currenty >= 41 And currenty <= 64, xval, largetop), IIf(currenty >= 26 And currenty <= 64, xval, largetop)), IIf(currenty >= 22 And currenty <= 49, largetop = xval, largetop)), largetop)

'----------COMMENTS TO EXPLAIN DESIRED OUTCOME-------
'If the xval is greater than the highest x value (largetop),
'And if this is for RED or BLUE machines,
'And if on 18 in. material,
'And within the correct range on the material, xval. (largetop should be the value of xval)
'If on 24 in. material (not 18 in.),
'And within the correct range for 24 in. material, xval. (largetop should be the value of xval)
'If not for RED or BLUE machines (GREEN machine, then),
'If within the correct range, (both 18 in. and 24 in. are in the same range)
'largetop should be the value of xval.
'The remaining false statements keep current value.

1 个答案:

答案 0 :(得分:1)

好吧,所以当我发布这个问题时,我想出来了。第一个工作正常,而这个没有,所以我开始怀疑这是不是我的问题,它是。错误是我基本上做了一个

的陈述
largetop = largetop = xval

以粗体显示(如果在代码中,粗体不显示):

largetop = IIf(xval&gt; largetop,IIf(范围(&#34; B2&#34;)。值=&#34; RED或BLUE&#34;,IIf(材料= 18,IIf(currenty&gt; = 41并且currenty&lt; = 64,xval,largetop),IIf(currenty&gt; = 26并且currenty&lt; = 64,xval,largetop)),IIf(currenty&gt; = 22并且currenty&lt; = 49, largetop = xval ,largetop)),largetop)

将其更改为 xval 修复了问题!希望有人会觉得这很有用......