我想從窗體中的所有組合框中排除空白行,但找不到實際的方式。我想出了這個例子:如何避免在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
爲什麼不直接刪除前手的空白,或過濾非空白,並通過 –
@MacroMan使用'UsedRange.SpecialCells(xlCellTypeVisible)'循環是有風險的這個解決方案將混亂的行列參考?例如。第2行第5行用於從第4行第5行中提取數據等。否則,它的神建議 – Krusing
@Krusing'SpecialCells(xlCellTypeVisible)'不要混淆範圍,範圍只包含可見單元格,它就像範圍。如果選擇Range(「A1:A7」),並且只有行A2 A3 A5有值,則返回A2 A3 A5。如果你想用我的指示找到這一行,用'爲範圍內的每個單元格'替換'for i = 0 to .Count'並使用'cell.row'而不是'i'來獲得行 –