实例需求:用户窗体中有两个控件
- 列表框:ListBox1,支持多选
- 按钮:CommandButton1
现在需要记录用户在列表框中选择顺序(不考虑选中后再次点击取消选中的操作),如下图所示。
Dim objDic As Object
Private Sub UserForm_Initialize()
Dim i As Long
For i = 1 To 10
Me.ListBox1.AddItem CStr(i)
Next
Set objDic = CreateObject("scripting.dictionary")
End Sub
Private Sub ListBox1_Change()
Dim i As Long, sKey As String
For i = 0 To ListBox1.ListCount - 1
sKey = ListBox1.List(i)
If ListBox1.Selected(i) Then
If Not objDic.exists(sKey) Then
objDic(sKey) = ""
End If
Else
If objDic.exists(sKey) Then
objDic.Remove sKey
End If
End If
Next i
End Sub
Private Sub CommandButton1_Click()
MsgBox Join(objDic.keys, ",")
End Sub
【代码解析】