如何避免在VBA中使用过多的if语句?

时间:2015-08-03 10:50:37

标签: vba if-statement

我想从表单中的所有ComboBox中排除空行,​​但找不到实际的方法。我想出了这个例子:

Dim Foo as Worksheet: Foo = Sheets("Foo")

With UserForm
    'The ComboBoxes have unique names, this code is just an example
    For i = 0 To Foo.UsedRange.Rows.Count
        If Foo.Cells(i + 1, 1) <> "" Then
            .ComboBoxFoo.AddItem (Foo.Cells(i + 1, 1))
        End If
        If Foo.Cells(i + 1, 2) <> "" Then
            .ComboBoxBar.AddItem (Foo.Cells(i + 1, 2))
        End If
        If Foo.Cells(i + 1, 3) <> "" Then
            .ComboBoxBaz.AddItem (Foo.Cells(i + 1, 3))
        End If

        '[etc. etc.]

    Next

End With

我的表单中有很多ComboBox,所有上述语句看起来都一样。必须有一种更有效的方式吗?

使用

解决空白唯一问题
Dim Foo As Worksheet: Foo = Sheet("Foo")
Dim Unique As Boolean

With UserForm
    'The ComboBoxes have unique names, this code is just an example
    For i = 0 To Foo.UsedRange.Rows.Count
        If Not IsEmpty(Foo.Cells(i + 1, 1) Then
            Unique = True
            For j = 0 To .ComboBoxFoo.ListCount - 1
                If .ComboBoxFoo.List(j) = Foo.Cells(i + 1, 1) Then
                    Unique = False
                Else: Unique = True
                End If
            Next j
            If Unique Then .ComboBoxFoo.AddItem (Foo.Cells(i + 1, 1))
        End If


        '[etc. etc.]

    Next i

End With

2 个答案:

答案 0 :(得分:4)

您可以尝试以下代码:

Dim Foo As Worksheet: Foo = Sheets("Foo")

With UserForm
    For i = 0 To Foo.UsedRange.Rows.Count
        For j = 1 To 10
            If Foo.Cells(i + 1, j) <> "" Then
                Call .Controls("ComboBox" & j).AddItem(Foo.Cells(i + 1, j))
            End If
        Next j
    Next

End With

它使用嵌套在第一个中的第二个For ... Next循环。使用UserForm的.Controls集合按名称引用组合框。

答案 1 :(得分:1)

如何:

Sub SO()
    For Each cell In Intersect(ActiveSheet.UsedRange, Range("A:C")).Cells
        If Not cell.Value = "" Then AssignToCB cell.Column, cell.Value
    Next
End Sub

Private Sub AssignToCB(cbNumber As Integer, value As String)
    Select Case cbNumber
        Case 1: ComboBoxFoo.AddItem value
        Case 2: ComboBoxBar.AddItem value
        Case 3: ComboBoxBaz.AddItem value
    End Select
End Sub