ラブびあ

ビール。ときどきラブ

ListBoxの項目を「上へ」「下へ」

UserFormにListBoxとSpinButtonをポトリペタして以下のコードを貼り付けます。

Option Explicit

Private Sub UserForm_Initialize()
    ListBox1.MultiSelect = fmMultiSelectExtended
    Dim i As Long
    For i = 1 To 10
        ListBox1.AddItem "hoge:" & i
    Next
End Sub

Private Sub SpinButton1_SpinUp()
    Call UpSelectedItems(ListBox1)
End Sub

Private Sub SpinButton1_SpinDown()
    Call DownSelectedItems(ListBox1)
End Sub

Private Sub UpSelectedItems(l As MSForms.ListBox)
    Dim i As Long
    For i = 0 To l.ListCount - 1
        Call Swap(l, i, i - 1)
    Next
End Sub

Private Sub DownSelectedItems(l As MSForms.ListBox)
    Dim i As Long
    For i = l.ListCount - 1 To 0 Step -1
        Call Swap(l, i, i + 1)
    Next
End Sub

Private Sub Swap(l As MSForms.ListBox, a As Long, b As Long)
    If a < 0 Or a > l.ListCount - 1 Then Exit Sub
    If b < 0 Or b > l.ListCount - 1 Then Exit Sub
    If a = b Then Exit Sub
    
    'Index:a が選択されていて Index:b が選択されていないとき、aとbを入れ替える
    If l.Selected(a) And Not l.Selected(b) Then
        Dim v As Variant
        v = l.List(a)
        l.RemoveItem a
        l.AddItem v, b
        l.Selected(a) = False
        l.Selected(b) = True
    End If
End Sub