首页 > 解决方案 > 让一系列 Excel 列表框控件无缝协作

问题描述

我正在用 Excel 开发一个应用程序,它允许用户通过从大量不同的 PLC 模块中进行选择来设置他们的 PLC IO 配置。通过依次选择制造商、设备系列、设备类型和模块名称来选择模块。每个属性选择对应一个不同的 ListBox 控件。每个 ListBox 的 ListFillRange 由前一个 ListBox 控制。例如,当我单击第一个 ListBox 以选择我的制造商时,我的 VBA 代码会清除以前的设备系列 ListFillRange,并使用新选择的制造商的所有设备系列重新填充它。此外,每个 ListBox 都使用一个特定的范围,因为它是 ListFillRange。可能是我可以使用 VBA 更直接地填充每个 ListBox 选择列表,但我无法弄清楚如何做到这一点。每个 ListBox 使用 ListBox_Click() 事件来运行其代码。我遇到的问题如下。

以下是单击 Device Family ListBox 时运行的代码示例。它将清除模块类型列表填充范围并使用新选择的设备系列中的所有模块类型重新填充它。

Private Sub ListBox2_Click()
Dim row As Integer
row = 2
Dim totalRows As Integer
Dim ModuleTypes(30) As Variant
Dim ArrayIndex As Integer
ArrayIndex = 0
totalRows = ThisWorkbook.Sheets("Tables").Cells(2, 5).Value

'Clear the Module Type selection list on the PLC Module Data Sheet.
'ThisWorkbook.Sheets("PLC Module Data").Range("C2:C500").Clear

'Clear the Table Name search result list on the PLC Module Data Sheet.
ThisWorkbook.Sheets("PLC Module Data").Range("I2:L500").Clear 

'Search the Table Name sheet for all entries fromm the selected MFG and with the selected Family and paste them onto the PLC Module Data Sheet.
For i = 2 To totalRows
    If (ThisWorkbook.Sheets("Tables").Cells(i, 2).Value = ListBox1.Value) And (ThisWorkbook.Sheets("Tables").Cells(i, 3).Value = ListBox2.Value) Then
    ThisWorkbook.Sheets("PLC Module Data").Cells(row, 9).Value = ThisWorkbook.Sheets("Tables").Cells(i, 1).Value
    ThisWorkbook.Sheets("PLC Module Data").Cells(row, 10).Value = ThisWorkbook.Sheets("Tables").Cells(i, 2).Value
    ThisWorkbook.Sheets("PLC Module Data").Cells(row, 11).Value = ThisWorkbook.Sheets("Tables").Cells(i, 3).Value
    ThisWorkbook.Sheets("PLC Module Data").Cells(row, 12).Value = ThisWorkbook.Sheets("Tables").Cells(i, 4).Value
    row = row + 1
End If
Next I

'Form an array of all unique Module Types within the Table search results list.
For i = 2 To ThisWorkbook.Sheets("PLC Module Data").Cells(2, 13).Value
If ArrayTest(ModuleTypes, ThisWorkbook.Sheets("PLC Module Data").Cells(i, 12).Value) Then
    ModuleTypes(ArrayIndex) = ThisWorkbook.Sheets("PLC Module Data").Cells(i, 12).Value
    ArrayIndex = ArrayIndex + 1
End If
Next i

'Copy the ModuleTypes Array into the Module Type selection list on the PLC Module Data Sheet.
For i = 0 To UBound(ModuleTypes)
ThisWorkbook.Sheets("PLC Module Data").Cells(2 + i, 3).Value = ModuleTypes(i)
Next i

'Clear the Temp search result list on the PLC Module Data Sheet.
ThisWorkbook.Sheets("PLC Module Data").Range("U2:X500").Clear

如果有人知道我如何解决上面列出的问题并让 ListBox 集无缝协作,我将不胜感激。谢谢。

标签: excelvbalistbox-control

解决方案


感谢大家的反馈。我让他们使用评论中提到的标志方法工作。


推荐阅读