【发布时间】:2021-10-16 20:13:45
【问题描述】:
我有一个包含以下代码的用户表单。基本上它的作用是如果用户选择一个标题,然后单击 commandButton2 将所选电影标题插入到标题框和数组中。现在我制作了另一个按钮commandButton3,用户可以从标题框中选择要删除的标题,但我正在努力从我正在构建的数组中删除它。提前致谢。
Public SelectedTitles As Variant, ArrCount As Long, EnableEvents As Boolean
Private Sub CommandButton1_Click()
'Done Button
Me.Hide
End Sub
Private Sub CommandButton2_Click()
'User has indicated they want to add the currently selected item to the list
If Not EnableEvents Then Exit Sub
If ArrCount = 0 Then 'First item, create the array
SelectedTitles = Array("")
Else
ReDim Preserve SelectedTitles(UBound(SelectedTitles) + 1) 'Next items, add one more space in the array
End If
'Add the selected title to the array
SelectedTitles(ArrCount) = ComboBox1.Value
ListBox1.AddItem (SelectedTitles(ArrCount))
'Increment the counter
ArrCount = ArrCount + 1
'Reset the checkbox and the combobox
EnableEvents = False
CommandButton2.Value = False
ComboBox1.Value = ""
EnableEvents = True
End Sub
Private Sub CommandButton3_Click()
For i = ListBox1.ListCount - 1 To 0 Step -1
If ListBox1.Selected(i) Then
ListBox1.RemoveItem i
If SelectedTitles() = i Then
SelectedTitles() = "n/a"
End If
ArrCount = ArrCount - 1
End If
Next i
EnableEvents = False
CommandButton3.Value = False
ComboBox1.Value = ""
EnableEvents = True
End Sub
Private Sub CommandButton4_Click()
ListBox1.Clear
Erase SelectedTitles
ArrCount = 0
EnableEvents = False
CommandButton4.Value = False
ComboBox1.Value = ""
EnableEvents = True
End Sub
Private Sub ListBox1_Click()
End Sub
Private Sub UserForm_Initialize()
EnableEvents = True
End Sub
【问题讨论】:
-
您需要将数组复制到没有选择元素的新数组中。最好看看使用集合。 docs.microsoft.com/en-us/office/vba/language/reference/…
-
你不能从列表框中填充数组吗?
-
@Norie 我什么时候会这样做。如果我要这样做,那么我想我必须将我拥有的命令按钮 2 的代码放在命令按钮 1 中,这将基于列表框创建数组?