Excel VBA基于Listbox2选择填充Listbox1

时间:2015-07-21 14:57:06

标签: excel-vba vba excel

我正在尝试找出基于第二个列表框中的选择来填充列表框的正确代码。我会尽力解释我的问题。我有一个工作表,其中有两列填充如下。

(COLUMN A)    (COLUMN B)
PART NUMBER:  LOCATION:
PART A        LOC1,LOC7,LOC12,LOC21
PART B        LOC2,LOC8,LOC13,LOC22
PART C        LOC6,LOC9,LOC18,LOC20

我希望能够使用" PART NUMBER"填充ListBox1。列,当我点击" PART A"我只从ListBox2中的(B列)获得了一个位置项列表。我希望这是有道理的,有人可以帮助我。提前谢谢。

填充我的ListBox:

Dim rngName As Range
Dim ws As Worksheet
Dim i As Integer

Set ws = Worksheets("Sheet2")
For i = 1 To ws.Cells(ws.Rows.Count, 1).End(xlUp).Row Step 1
If ws.Cells(i, 1).Value <> vbNullString Then Me.LstPartNum.AddItem    ws.Cells(i, 1).Value
Next i

测试用逗号填充和分割:

UserForm1.LstPartNum.List = Split("LOC1,LOC7,LOC12,LOC21", ",")

1 个答案:

答案 0 :(得分:2)

在零件编号组合框的更改事件中,请执行以下操作。

Dim ws As Excel.Worksheet
Dim lRow As Long

Set ws = Worksheets("Sheet2")
lRow = 1

'Loop through the rows
Do While lRow <= ws.UsedRange.Rows.count
    'Check if Column A has the value of the selected part number.
    If ws.Range("A" & lRow).Value = LstPartNum.Text Then
        UserForm1.LstLocation.Clear
        'Load the locations
        UserForm1.LstLocation.List = Split(ws.Range("B" & lRow).Value, ",")
        Exit Do
    End If
lRow = lRow + 1
Loop

如果您的UserForm1.LstPartNum.List = Split()无法加载列表,则此处是循环拆分数组的代码。

Dim szLocs() As String
Dim i as integer

szLocs= Split(ws.Range("B" & lRow).Value, ",")

i = 0
'Loop though each token
Do While i <= UBound(szPieces)
    UserForm1.LstPartNum.Additem szPieces(i)
i = i + 1
Loop