引言
列表框(ListBox)是最常用的VBA窗体控件之一。实现列表框项目的上移下移功能,可以达到自定义排序的效果。
UI设计
这里主要使用到了一个列表框和两个按钮控件,主界面设计和相关控件命名如下所示。
VBA实现代码
1.窗体初始化事件
Private Sub UserForm_Initialize()
ListBox1.AddItem "张三"
ListBox1.AddItem "李四"
ListBox1.AddItem "王五"
ListBox1.AddItem "赵六"
ListBox1.AddItem "孙七"
ListBox1.AddItem "周八"
ListBox1.AddItem "吴九"
ListBox1.AddItem "郑十"
End Sub
2.上移按钮单击事件
Private Sub cmdbUp_Click()
Dim i As Integer
' 确保ListBox有选中的项目
If ListBox1.ListIndex <> -1 Then
' 遍历列表框的项目
For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) And i <> 0 Then
temp = ListBox1.List(i)
ListBox1.List(i) = ListBox1.List(i - 1)
ListBox1.List(i - 1) = temp
'保持列表框选中的项目不变
ListBox1.Selected(i - 1) = True
Exit For
End If
Next i
End If
End Sub
3.下移按钮单击事件
Private Sub cmdbDown_Click()
Dim i As Integer
' 确保ListBox有选中的项目
If ListBox1.ListIndex <> -1 Then
' 遍历列表框的项目
For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) And i <> ListBox1.ListCount - 1 Then
tempp = ListBox1.List(i)
ListBox1.List(i) = ListBox1.List(i + 1)
ListBox1.List(i + 1) = tempp
'保持列表框选中的项目不变
ListBox1.Selected(i + 1) = True
Exit For
End If
Next i
End If
End Sub
本文暂时没有评论,来添加一个吧(●'◡'●)