Excel – Is it possible to sort a table by entry modification date? Specifically, how to access from VBA the last modification time of an object

date-modifiedmicrosoft excelmicrosoft wordsortingvisual basic

I have a MS Word document where I accumulate and frequently modify certain data in a very long table. So I would like to sort the data by latest modification time in the rows. Of course if I add a column where I enter the modification time by hand this would work but I would like to avoid this if possible.

OK as the question has been put on hold with the request to make it more concrete, I am trying to modify it accordingly.

What I specifically want (and then I can do it myself) is this:

Since MS Word has features like change tracking, each modified portion of text must have its last modification time recorded in some form.

My question is then – how can I access this information from within a Visual Basic macro? I mean something like ThisTable.ThisCell.ModificationTime() or ThatTable.CurrentRow.LastModificationSessionTime() or something similar.

Best Answer

This is for an Excel worksheet. Data is entered or modified in column A. The macro automatically enters the date/time in column B. The macro then sorts column A & B by column B, putting the most recent at the top.

Enter the following event macro in the worksheet code area:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim A As Range
    Dim AB As Range
    Set A = Range("A:A")
    Set AB = Range("A:B")

    If Intersect(Target, A) Is Nothing Then Exit Sub
    If Target.Count > 1 Then Exit Sub
    Application.EnableEvents = False
        Target.Offset(0, 1) = Now
        AB.Sort Key1:=Range("B1"), Order1:=xlDescending, Header:=xlNo, _
            OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
            DataOption1:=xlSortNormal
    Application.EnableEvents = True
End Sub

Because it is worksheet code, it is very easy to install and automatic to use:

  1. right-click the tab name near the bottom of the Excel window
  2. select View Code - this brings up a VBE window
  3. paste the stuff in and close the VBE window

If you have any concerns, first try it on a trial worksheet.

If you save the workbook, the macro will be saved with it. If you are using a version of Excel later then 2003, you must save the file as .xlsm rather than .xlsx

To remove the macro:

  1. bring up the VBE windows as above
  2. clear the code out
  3. close the VBE window

To learn more about macros in general, see:

http://www.mvps.org/dmcritchie/excel/getstarted.htm

and

http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx

To learn more about Event Macros (worksheet code), see:

http://www.mvps.org/dmcritchie/excel/event.htm

Macros must be enabled for this to work!

Related Question