如何颠倒行的顺序

我尝试编写一个macros,它将在我的Excel工作表中颠倒行的顺序,但不幸的是我失败了。 我甚至不知道如何开始。 我将非常感谢任何帮助或提示如何做到这一点。

select你的行并运行这个macros:

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注释掉。

我稍微简化了Wallys代码并将其更改了一下,以便将行号作为input参数:

 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 

托比