Excel VBA: Sort, then Copy and Paste

前端 未结 2 1878
庸人自扰
庸人自扰 2021-01-22 05:26

All, I need to write a macro that does the following:

  1. On entry data into the last blank cell in column E, sort the entire worksheet by column E

2条回答
  •  佛祖请我去吃肉
    2021-01-22 06:16

    Regarding 1, 2a, and 2b: It's more straightforward to do the copying before sorting. That way, the copied value will be sorted along with the rest.

    Private Sub Worksheet_Change(ByVal Target As Range)
        If Not (Application.Intersect(Worksheets("Sheet1").Range("E:E"), Target) _
            Is Nothing) Then
            ' First copy
            Target.Offset(0, -1).Copy Destination:=Target.Offset(0, -4)
            ' Then sort
            DoSort
        End If
    End Sub
    

    This leaves the question (2c) of how to move the active cell to the appropriate row after the rows have been sorted. Presumably, you want the user to input further data in column F?

    Again, the most straightforward solution would be to have this input happen first, and then do the sorting. This would have the added benefit that the user wouldn't have the input row jump around between inputting data in column E and column F. The sorting could even happen just once, after all the data has been entered by the user.

    Of course, the above is more a design suggestion than a solution to your specific task 2c. If moving the active cell after sorting is really what you want, then the solution will inevitably be more complicated. Excel's Sort method does not return an index, to locate your entries after sorting. You will have to make an index / "serial number" yourself and search for it after sorting. This works:

    Private Sub Worksheet_Change(ByVal Target As Range)
        Dim newIndex As Long
        If Not (Application.Intersect(Worksheets("Sheet1").Range("E:E"), Target) _
            Is Nothing) Then
            ' Index the new entry in column B. (You can put the index elsewhere.)
            newIndex = WorksheetFunction.Max(Range("B:B")) + 1
            Target.Offset(0, -3).Value = newIndex
            ' Copy the entry.
            Target.Offset(0, -1).Copy Destination:=Target.Offset(0, -4)
            ' Sort
            DoSort
            ' Search for the new index after sorting. Select cell in column 6 (F).
            Cells(WorksheetFunction.Match(newIndex, Range("B:B"), 0), 6).Select
        End If
    End Sub
    

    Making an index is not strictly necessary if all your entries are unique (i.e. no duplicates); you could in principle just search for the entry itself. However, if there can be duplicates, then searching for the entry itself (rather than its index) will be more messy, and may lead to unwanted behaviour unless it's programmed just right. I find it much cleaner to just use an index.

提交回复
热议问题