Excel宏用于行与行重新排序的逐行比较

时间:2015-03-03 02:56:05

标签: excel vba excel-vba

这是我第一次尝试创建一个宏,所以提前抱歉我对这个主题缺乏了解。我试图在线关注教程和示例,但我没有太多运气。

我想创建一个宏,如果行中的某些值小于上一行中的相应值,则可以将整行移动到上一行之上。

我尝试发布我正在使用的Excel工作表的图片,但我没有足够的声誉。

逻辑将是这样的:

IF --- Column2(row_i)<列2(row_i-1)

AND --- Column3(row_i)< Column4(row_i-1)

THEN

在row_i-1

上方插入一个空白行

复制row_i并将其粘贴到空白行

删除原始row_i

返回列表顶部并重新开始搜索

ELSE ---移至row_i + 1}

以下是我目前的情况:

Sub PrioritySort()
Dim i As Integer

For i = 11 To 17
    If Cells(i, 2) < Cells((i - 1), 2) Then
         If Cells(i, 3) < Cells((i - 1), 4) Then
         //insert row_i above row_i-1
    Else
         Next i
End Sub

如果有人愿意提供帮助,我们将不胜感激!

2 个答案:

答案 0 :(得分:0)

//在row_i-1上面插入row_i就像:

Rows(i).Select
Selection.Cut
Rows(i-1).Select
Selection.Insert Shift:=xlDown

...还要记住“结束如果”以关闭多行If语句。

答案 1 :(得分:0)

我们来一个样本:

column1 column2 column3 column4
4       4       4       4
3       3       3       3
2       2       2       2
1       1       1       1

我们想重新排序。我们的最终结果应该是这样的

column1 column2 column3 column4
1       1       1       1
2       2       2       2
3       3       3       3
4       4       4       4

<强>宏

    Sub Macro3()

        Dim NoOfTimesChanged As Integer

        ' attempt to reorder rows and find out if reordering
        ' was done or not
        NoOfTimesChanged = ReOrderRows()

        ' keep on reording until there is nothing else to reorder
        Do While NoOfTimesChanged > 0
            NoOfTimesChanged = ReOrderRows()
        Loop

    End Sub

<强>功能

    ' Reorder all rows based on certain condition

    ' Returns:  0 or 1 to the caller
    '           0 is returned when no reording was necessary
    '           1 is returned when reordering was necessary

    Function ReOrderRows() As Integer

    Dim ReOrdered As Integer
    ReOrdered = 0

    ' Lets start from row #3 and compare with row #2
    ' Remember that row #1 has headers
    For i = 3 To 5

        ' IF--- Column2(row_i) < Column2(row_i-1)
        ' AND--- Column3(row_i) < Column4(row_i-1)
        If Cells(i, 2) < Cells(i - 1, 2) And _
           Cells(i, 3) < Cells(i - 1, 4) Then

            ' select the current row and cut it
            Rows(i & ":" & i).Select
            Selection.Cut

            ' select the above row insert the cut-rows
            ' making sure the current selection is moved down
            Rows(i - 1 & ":" & i - 1).Select
            Selection.Insert shift:=xlDown

            ' mark this flag to 1 so as to inform
            ' the caller function that reordering
            ' was performed
            ReOrdered = 1

        End If

    Next i

    ReOrderRows = ReOrdered

    End Function

试一试。请注意,我只使用了4行+ 1个标题行,因此for循环从3变为5.您可以根据需要更改此代码。