我尝试编写一个可以反转Excel工作表中行的顺序的宏,但不幸的是我失败了。我甚至不知道如何开始。如果有任何帮助或提示,我将非常感激。
答案 0 :(得分:4)
选择行并运行此宏:
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。
答案 1 :(得分: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
托比