2013-07-29 191 views
0

我嘗試編寫一個宏,它可以顛倒我Excel工作表中的行順序,但不幸的是我失敗了。我甚至不知道如何開始。我會非常感謝任何幫助或提示如何做到這一點。如何顛倒行的順序

+7

插入一列,與** 1,2,3填充4 **等,直到您想要倒轉的行的末尾。然後選擇您的數據,包括您剛剛添加的列,然後反向排序(從最大到最小)。使用宏記錄器查看代碼是否需要多次執行 – SeanC

+4

顯示失​​敗代碼.. – matzone

+3

第1步:將行添加到數組變量,同時從Rows.Count迭代到1.第2步:將數組寫入工作表。 –

回答

3

選擇行並運行該宏:

Sub ReverseList() 
    Dim firstRowNum, lastRowNum, thisRowNum, lowerRowNum, length, count As Integer 
    Dim showStr As String 
    Dim thisCell, lowerCell As Range 
    With Selection 
     firstRowNum = .Cells(1).Row 
     lastRowNum = .Cells(.Cells.count).Row 
    End With 
    showStr = "Going to reverse rows " & firstRowNum & " through " & lastRowNum 
    MsgBox showStr 

    showStr = "" 
    count = 0 
    length = (lastRowNum - firstRowNum)/2 
    For thisRowNum = firstRowNum To firstRowNum + length Step 1 
     count = count + 1 
     lowerRowNum = (lastRowNum - count) + 1 
     Set thisCell = Cells(thisRowNum, 1) 
     If thisRowNum <> lowerRowNum Then 
      thisCell.Select 
      ActiveCell.EntireRow.Cut 
      Cells(lowerRowNum, 1).EntireRow.Select 
      Selection.Insert 
      ActiveCell.EntireRow.Cut 
      Cells(thisRowNum, 1).Select 
      Selection.Insert 
     End If 
     showStr = showStr & "Row " & thisRowNum & " swapped with " & lowerRowNum & vbNewLine 
    Next 
    MsgBox showStr 
End Sub 

註釋掉MSGBOX如果你不喜歡的通知。

0

我簡化Wallys代碼一點,改變了它,使得它具有行號作爲輸入參數:

Sub ReverseList(firstRowNum As Integer, lastRowNum As Integer) 

    Dim upperRowNum, lowerRowNum, length As Integer 

    length = (lastRowNum - firstRowNum - 2)/2 
    For upperRowNum = firstRowNum To firstRowNum + length Step 1 
    lowerRowNum = lastRowNum - upperRowNum + firstRowNum 

    Cells(upperRowNum, 1).EntireRow.Cut 
    Cells(lowerRowNum, 1).EntireRow.Insert 
    Cells(lowerRowNum, 1).EntireRow.Cut 
    Cells(upperRowNum, 1).EntireRow.Insert 
    Next 
End Sub 

託比