0

我尝试编写一个宏来反转我的 Excel 工作表中的行顺序,但不幸的是我失败了。我什至不知道如何开始。对于如何操作的任何帮助或提示,我将不胜感激。

4

3 回答 3

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。

于 2013-07-29T15:52:54.680 回答
1

我稍微简化了 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

托比

于 2016-05-20T20:18:59.883 回答
0

我用 Range 参数扩展了 Tobag 的答案,并使所有参数都是可选的:

Sub ReverseRows(Optional rng As range = Nothing, Optional firstRowNum As Long = 1, Optional lastRowNum As Long = -1)

    Dim i, firstRowIndex, lastRowIndex As Integer
    
    ' Set default values for dynamic parameters
    If rng Is Nothing Then Set rng = ActiveSheet.UsedRange
    If lastRowNum = -1 Then lastRowNum = rng.Rows.Count
    
    If firstRowNum <> 1 Then
        ' On each loop, cut the last row and insert it before row 1, 2, 3, and so on
        lastRowIndex = lastRowNum
        For i = firstRowNum To lastRowNum - 1 Step 1
            firstRowIndex = i
            rng.Rows(lastRowIndex).EntireRow.Cut
            rng.Rows(firstRowIndex).EntireRow.Insert
        Next
    Else
        ' Same as above, except handle different Insert behavior.
        ' When inserting to row 1, the insertion goes above/outside rng,
        ' thus the confusingly different indices.
        firstRowIndex = firstRowNum
        For i = firstRowNum To lastRowNum - 1 Step 1
            lastRowIndex = lastRowNum - i + 1
            rng.Rows(lastRowIndex).EntireRow.Cut
            rng.Rows(firstRowIndex).EntireRow.Insert
        Next
    End If
  
End Sub
于 2021-09-22T18:25:14.033 回答