2014-10-02 76 views
0

是否可以使用列表框來更改工作表中行的順序?我已經在網上搜索了大約一個小時而沒有重新打開。我正在使用以下代碼執行任務:有關列表框的Excel VBA(用戶表單)

Private Sub UserForm_Initialize() 
ListBox1.RowSource = "Sheet1!A1:A15" 
End Sub 

Option Explicit 
Const UP As Integer = -1 
Const DOWN As Integer = 1 

Private Sub SpinButton1_SpinUp() 

If Me.ListBox1.ListCount > 1 Then 
    Call MoveListItem(UP, Me.ListBox1) 
End If 

End Sub 

Private Sub SpinButton1_SpinDown() 

If Me.ListBox1.ListCount > 1 Then 
    Call MoveListItem(DOWN, Me.ListBox1) 
End If 

End Sub 

Private Sub MoveListItem(ByVal intDirection As Integer, _ 
ByRef ListBox1 As ListBox) 

Dim intNewPosition As Integer 
Dim strTemp As String 

intNewPosition = ListBox1.ListIndex + intDirection 
strTemp = ListBox1.List(intNewPosition) 

If intNewPosition > -1 _ 
And intNewPosition < ListBox1.ListCount Then 

    'Swap listbox items 
    ListBox1.List(intNewPosition) = ListBox1.Value 
    ListBox1.List(intNewPosition - intDirection) = strTemp 
    ListBox1.Selected(intNewPosition) = True 

End If 

End Sub 

希望somone能給我一個提示!

更新!

我想是的,如果我例如有一列在我的工作表中這些值:

week1

week2

譯員更加

week4

然後我想用ListBox中的SpinButton重新設置這些值的順序;

week2

week4

week1

譯員更加

+0

你是什麼意思改變行的順序?排序?你能提供你的數據之前和之後嗎?這可以幫助我們知道你想要做什麼。 – guitarthrower 2014-10-02 17:03:41

+0

@guitarthrower我已經更新了我的問題,希望你能幫忙! – 2014-10-02 17:12:42

回答

1

你肯定能做到這一點!

下面是一個簡單的代碼,這是否在一般情況下,我將它留給你把這個需要的地方:

For i = 0 To ListBox1.ListCount - 1 
    ActiveWorkbook.Sheets("Sheet1").Range("A" & CStr(i + 1)).Value = ListBox1.List(i) 
Next i 

你可能需要改變的是裏面的for循環更好地反映你自己的代碼。要寫入特定的範圍,只需添加任何你想要的起始行號!