2011-07-14 236 views
0

我有兩列,其中一列有狀態,另一列有名字。我想要做的是通過選項按鈕選擇staus,並根據選項名稱選擇並填充到列表框/組合框中。動態填充列表框

Private Sub CommandButton1_Click() 
Dim ListOfNames() As Variant 
Dim ws As Worksheet 
Set ws = Worksheets(2) 
Dim Count As Long 
Dim StatusVal As String 
Dim j As Long, k As Long, iRow As Long 

j = 0 
k = 0 
If OptionButton1.Value = True Then 
StatusVal = "Retired" 
j = j + 1 
ElseIf OptionButton2.Value = True Then 
StatusVal = "Employed" 
j = j + 1 
ElseIf OptionButton3.Value = True Then 
StatusVal = "On Leave" 
j = j + 1 
Else 
ListVal = "Not Selected" 
End If 

'Count the number of rows in excel 
iRow = ws.Cells(Rows.Count, 1) _ 
    .End(xlUp).Offset(1, 0).Row 

ReDim ListOfNames(iRow, j) 
' first row for header 
For Count = 2 To iRow - 1 Step 1 
    If StatusVal = ws.Cells(Count, 15).Value Then 
    k = k + 1 
    ListOfNames(k, j) = ws.Cells(Count, 1).Value 
    End If 
Next 
With ListBox1 
    .list() = ListOfAccounts 
End With 
End Sub 

回答

0

我希望這有助於!我發現了兩個問題。

  • 對於沒有設置的列表框的分配,有必要的屬性。由於您有多維數組,因此我使用AddItem方法添加到列表框。
  • 您將ListOfAccounts分配給列表而不是您聲明的ListOfEmployees。

我還添加了

ListBox1.Clear 

要清除的內容之間按下按鈕。

Private Sub CommandButton1_Click() 

Dim ListOfNames() As Variant 

Dim Count As Long 
Dim StatusVal As String 
Dim j As Long, k As Long, iRow As Long 
ListBox1.Clear 
j = 0 
k = 0 
If OptionButton1.Value = True Then 
    StatusVal = "Retired" 
    j = j + 1 
ElseIf OptionButton2.Value = True Then 
    StatusVal = "Employed" 
    j = j + 1 
ElseIf OptionButton3.Value = True Then 
    StatusVal = "On Leave" 
    j = j + 1 
Else 
    ListVal = "Not Selected" 
End If 

'Count the number of rows in excel 
iRow = ws.Cells(Rows.Count, 1) _ 
     .End(xlUp).Offset(1, 0).Row 
ReDim ListOfNames(iRow, j) 
' first row for header 
For Count = 2 To iRow - 1 Step 1 
    If StatusVal = ws.Cells(Count, 15).Value Then 
     k = k + 1 
     ListOfNames(k, j) = ws.Cells(Count, 15).Value 
    End If 
Next 
Dim z 
For z = 0 To k 
    Me.ListBox1.AddItem (ListOfNames(z, j)) 
Next 
End Sub 
+0

謝謝安德魯,我無法解決這個問題,所以使用additem屬性,但這增加了一個循環,並且隨着名稱數量的增加,性能變慢。 .list()函數不應該爲數組的值分配列表框是我的查詢。 –

+0

很可能是.list()函數期望一個一維數組,而您將它傳遞給一個二維數組。我會嘗試。我對內部知識不夠了解,知道分配數組是否比迭代更有效。 –