我正在VBA中的一个应用程序上,该应用程序从excel工作表中接收信息,填充一个下拉组合框,然后基于从该下拉框中选择的信息,检索用于匹配值的完整信息。有6个保管箱,我正在寻找一种方法来找出哪些保管箱具有值(不为空),而无需用相同的代码但条件不同(例如组合1和3具有值)重写数十个if语句,因此程序将仅根据这两个选定字段查找记录)
我知道这可以通过重写if语句来实现,但是我希望有一种更简单的方法,而无需花费数小时?
Private Sub Search_Page1_Click()
Dim year As String
Dim location As String
Dim snap As String
Dim city As String
Dim group As String
Dim endyear As String
year = Multipage1.Cmb_Year.Value
location = Multipage1.Cmb_Location.Value
snap = Multipage1.Cmb_Snapshot.Value
city = Multipage1.Cmb_City.Value
group = Multipage1.Cmb_Group.Value
endyear = Multipage1.Cmb_LeaseEnd.Value
If year = Empty And location = Empty And snap = Empty And city = Empty
And group = Empty And endyear = Empty Then
MsgBox ("Please fill in at least one field")
End If
End Sub
答案 0 :(得分:1)
如果您可以使用Collection
的ComboBox控件,则可以像这样自定义函数并像这样调用它:
Dim populatedBoxes as New Collection
Set populatedBoxes = GetPopulatedThings(Multipage1, "ComboBox")
Dim cb as MSForms.ComboBox
For Each cb in populatedBoxes
MsgBox cb.Value
Next
在您的代码中,您可以替换:
If year = Empty And location = Empty And snap = Empty And city = Empty And group = Empty And endyear = Empty Then
与此:
Set populatedBoxes = GetPopulatedThings(Multipage1, "ComboBox")
If populatedBoxes.Count = 0 Then Exit Sub
功能如下:
Private Function GetPopulatedThings(container As Object, Optional ctrlType As String = "ComboBox") As Collection
Dim c As New Collection
Dim ctrl As MSForms.Control
For Each ctrl In container.Controls
If TypeName(ctrl) = ctrlType Then
Select Case ctrlType
Case "ComboBox"
If ctrl.ListIndex > -1 Then
c.Add ctrl
End If
Case Else
' TBD
' Additional cases will require separate logic...
End Select
End If
Next
Set GetPopulatedThings = c
End Function