2015-08-03 93 views
0

我想從窗體中的所有組合框中排除空白行,但找不到實際的方式。我想出了這個例子:如何避免在VBA中使用太多if語句?

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 

我有很多ComboBoxes在我的表單中,上面的所有語句看起來都是一樣的。必須有更有效的方法嗎?

解決了空白獨特問題與

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 
+0

爲什麼不直接刪除前手的空白,或過濾非空白,並通過 –

+0

@MacroMan使用'UsedRange.SpecialCells(xlCellTypeVisible)'循環是有風險的這個解決方案將混亂的行列參考?例如。第2行第5行用於從第4行第5行中提取數據等。否則,它的神建議 – Krusing

+1

@Krusing'SpecialCells(xlCellTypeVisible)'不要混淆範圍,範圍只包含可見單元格,它就像範圍。如果選擇Range(「A1:A7」),並且只有行A2 A3 A5有值,則返回A2 A3 A5。如果你想用我的指示找到這一行,用'爲範圍內的每個單元格'替換'for i = 0 to .Count'並使用'cell.row'而不是'i'來獲得行 –

回答

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集合。

+0

我會如果我對組合框沒有獨特的名稱,就喜歡這個解決方案。對不起,沒有在我的問題中提到這一點。另外,有沒有一種按類型統計控件的方法? – Krusing

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