反向排列范围

时间:2019-03-11 15:26:20

标签: excel vba

我必须反转范围的行。我编写的代码在2分钟,18 s,587毫秒内还原了1000行x 1000列的范围。有人可以提供更快的代码吗?

平均时间1000行x 1000列:2分钟,18 s,587毫秒

(Intel i7-6700 4 GHz,32 GB RAM)(Windows 10 Home x64)(Excel Office 365 MSO(16.0.11328.20144)32位)

我不需要关闭计算,单元格没有公式。 GMalc代码很短而且非常快:8秒23毫秒,但是@Rory建议更快,就像罗恩所说的:1秒195毫秒!谢谢

Sub InvertRangeRows(ByRef rngRange_IO As Range)

Dim RowI&, RowRange&, RowArray&, RowFirst As Long
Dim RowLast&, ColumnFirst&, ColumnLast As Long
Dim ArrayRange As Variant, ArrayInverted As Variant
Dim RowCurrent As Variant

Application.ScreenUpdating = False

ArrayRange = rngRange_IO
ReDim ArrayInverted(1 To UBound(ArrayRange))

For RowI = UBound(ArrayRange) To LBound(ArrayRange) Step -1
    RowCurrent = Application.WorksheetFunction.Index(ArrayRange, RowI, 0)
    RowRange = RowRange + 1
    ArrayInverted(RowRange) = RowCurrent
Next RowI

With rngRange_IO
    RowFirst = .Row
    RowLast = RowFirst + UBound(ArrayRange) - 1
    ColumnFirst = .Column
    ColumnLast = ColumnFirst + UBound(ArrayRange, 2) - 1
End With

With rngRange_IO.Worksheet
    For RowI = RowFirst To RowLast
        RowArray = RowArray + 1
        .Range(.Cells(RowI, ColumnFirst), .Cells(RowI, ColumnLast)) _
          = ArrayInverted(RowArray)
    Next RowI
End With

Application.ScreenUpdating = False

End Sub

2 个答案:

答案 0 :(得分:1)

此代码在1分28秒内并没有快得多(1k x 1k),但是更容易。

Dim ws As Worksheet, lRow As Long, i As Long

Set ws = ThisWorkbook.Worksheets("Sheet1")
lRow = ws.Cells(Rows.Count, 1).End(xlUp).Row

Application.Calculation = xlCalculationManual
    For i = 2 To lRow
        ws.Cells(i, 1).EntireRow.Cut
        ws.Cells(1, 1).EntireRow.Insert Shift:=xlDown
    Next i
Application.Calculation = xlCalculationAutomatic

答案 1 :(得分:0)

我根据@Rory和Ron Rosenfeld的建议共享代码。我已经关闭了计算功能,以便可以包含公式。这是最快的代码:我的第一个代码是1.2 s对2'18.6“ !!!谢谢

Sub InvertRangeRows(ByRef rngRange_IO As Range)
Dim RowI&, RowCurrent&, ColumnI As Long
Dim ArrayRange As Variant, ArrayInverted As Variant

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

ArrayRange = rngRange_IO
ReDim ArrayInverted(1 To UBound(ArrayRange), 1 To UBound(ArrayRange, 2))

For RowI = UBound(ArrayRange) To 1 Step -1
    RowCurrent = RowCurrent + 1
    For ColumnI = 1 To UBound(ArrayRange, 2)
        ArrayInverted(RowCurrent, ColumnI) = ArrayRange(RowI, ColumnI)
    Next ColumnI
Next RowI

rngRange_IO = ArrayInverted

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True

End Sub