我有两列,其中一列有状态,另一列有名称。我想要做的是通过选项按钮选择状态,并根据选项选择名称并填充在列表框/组合框中。
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 :(得分:0)
我希望这有帮助!我发现了两个问题。
我还添加了一个
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