Excel VBA嵌套案例函数适用于多种条件

时间:2018-03-22 05:20:07

标签: excel vba excel-vba if-statement case

我有一个SQL查询,想要在Excel VBA中复制。我在使用多个案例陈述时遇到了麻烦

示例列

column(a) - segment_nbr

column(b) - ltv 

segment_nbr ltv 

1   2.1526521   
4   3.01348283  
1   1.49385324  
1   1.84731871  
1   1.29541322  
1   0.55659018  
2   2.33690417  
1   1.34068404  
2   1.54078719  
1   0.74087837  
3   1.93278303  
1   1.38347042  
4   1.64194326  

我想构建一个函数来复制以下示例嵌套if / case formula:

=if(and($A1=1,$B1<=0.9),100.01,IF(and($A1=1,$B1<=2.0),201.01,IF(and($A1=1,$B1<=3.0),-23.26,IF(and($A1=2,$B1<=0.9),-99.98,IF(and($A1=3,$B1<=1.3),199.98, IF(and($A1=4,$B1<=0.44),-32.43,IF(and($A1=4,$B1<=1.6),160.9,"" )))

我尝试了以下但不能正常工作:它没有采用segment_nb参数。

关于我如何纠正它的任何想法?

Function ltv_w(segment_nbr, ltv )

Select Case ltv 
    Case Is <= 0.9 And segment_nbr = 1
        ltv_w = 100.01
    Case Is <= 2.0 And segment_nbr = 1
        ltv_w = 201.01
    Case Is <= 3.0 And segment_nbr = 1
        ltv_w = -23.26
    Case Is <= 0.9 And segment_nbr = 2
        ltv_w = -99.98
    Case Is <= 1.3 And segment_nbr = 3
        ltv_w = 199.98
    Case Is <= 0.44 And segment_nbr = 4
        ltv_w = -32.43
    Case Is <= 1.6 And segment_nbr = 4
        ltv_w = 160.9

End Select

End Function

3 个答案:

答案 0 :(得分:1)

使用this.params.api.addItems([{blockKey: data[arrSize - 1].BlockKey , bpKey: this.businessPartnerId , bpName: this.businessPartnerName, itemKey: this.itemKey}]); ,仅检查Select Case ltv的值,它不像使用ltv并添加If,它会忽略第二个条件。< / p>

你可以&#34;作弊&#34; And一点,您可以使用Select Case,然后在下面嵌套修改您的代码:

Select Case True

尝试以下代码:

Case ltv <= 0.9 And segment_nbr = 1

答案 1 :(得分:0)

首先 - 改变检查顺序 在第一个案例级别检查segment_nbr,然后在第二级检查ltv

Function ltv_w(segment_nbr, ltv)

    Select Case segment_nbr
        Case 1
            Select Case ltv
                Case Is <= 0.9: ltv_w = 100.01
                Case Is <= 2#:  ltv_w = 201.01
                Case Is <= 3#:  ltv_w = -23.26
            End Select

        Case 2
        Case 3
        Case 4
    End Select
End Function

小心Case Is <=序列。

再一次...... 绝不比较双打的平等 因此,<= 3#等条件需要转换为Not > 3#

答案 2 :(得分:0)

根据我的理解,你也可以使用if else语句来实现这个东西,检查下面的代码它根据你的excel公式修改。

''''
Function ltv_w(segment_nbr, ltv)

Select Case segment_nbr
    Case Is = 1

    Select Case ltv
    Case Is <= 0.9
    ltv_w = -99.98

    Case Is <= 2#
    ltv_w = 201.01

    Case Is <= 3#
    ltv_w = -23.26

    Case Else
    ltv_w = ""

    End Select

    Case Is = 2

    Select Case ltv
    Case Is <= 0.9
    ltv_w = -99.98

    Case Else
    ltv_w = ""

    End Select

    Case Is = 3

    Select Case ltv
    Case Is <= 1.3
    ltv_w = 199.98

    Case Else
    ltv_w = ""

    End Select

    Case Is = 4

    Select Case ltv
    Case Is <= 0.44
    ltv_w = -32.43

    Case Is <= 1.6
    ltv_w = 160.9

    Case Else
    ltv_w = ""

    End Select

Case Else
ltv_w = ""

End Select
End Function

''