简化if语句

时间:2016-12-11 01:07:49

标签: vba if-statement simplify

我正在制作一个VBA项目,并希望简化以下if语句,因为我需要为每个人提供11次以上的这个。

'CTK opportunities
If result = "CTK" And ToggleButton1 = True Then Range("B4").Value = "X"
If result = "CTK" And ToggleButton2 = True Then Range("C4").Value = "X"
If result = "CTK" And ToggleButton3 = True Then Range("D4").Value = "X"
If result = "CTK" And ToggleButton4 = True Then Range("E4").Value = "X"
If result = "CTK" And ToggleButton5 = True Then Range("F4").Value = "X"
If result = "CTK" And ToggleButton6 = True Then Range("G4").Value = "X"
If result = "CTK" And ToggleButton7 = True Then Range("H4").Value = "X"
If result = "CTK" And ToggleButton8 = True Then Range("I4").Value = "X"
If result = "CTK" And ToggleButton9 = True Then Range("J4").Value = "X"
If result = "CTK" And ToggleButton10 = True Then Range("K4").Value = "X"
If result = "CTK" And ToggleButton11 = True Then Range("L4").Value = "X"
If result = "CTK" And ToggleButton12 = True Then Range("M4").Value = "X"

'Next person

3 个答案:

答案 0 :(得分:1)

除了在"CTK"上对测试进行分解之外,您还可以为ToggleButtons定义一个数组并对其进行迭代:

toggleButtons = Array(ToggleButton1, ToggleButton2, .... , ToggleButton12)

If(result = CTK) Then
    For i = 0 to UBound(toggleButtons)
        If toggleButtons[i] = True Then Cells(4, i+2).Value = "X"
    Next
End If 

答案 1 :(得分:1)

你可以试试这个:

-mpreferred-stack-boundary=5

答案 2 :(得分:0)

If result = "CTK" Then
    If ToggleButton1 = True Then
        Range("B4").Value= "X"
    ElseIf ToggleButton2 = True Then
        Range("C4").Value = "X"
    ElseIf...........etc