Type UndoAggregationDataType
    oldWorkbook As Workbook
    oldSheet As Worksheet
    oldLine1(5) As String
    oldLine2(5) As String
    oldRowIdx As Integer
End Type
Public vUndoAggregationData() As UndoAggregationDataType
Public vUndoAggregationDataLength As Integer

Sub assign_aggregate_keys()
' assign shortcut keys to "aggregate modality" Macro
    Application.MacroOptions Macro:="aggregate_modality", Description:="", ShortcutKey:="g"
    Application.MacroOptions Macro:="undo_aggregate_modality", Description:="" , ShortcutKey:="G"
End Sub

Sub aggregate_modality()
'
' aggregate_modality Macro
'
' Keyboard Shortcut: Ctrl+g
'
    r = ActiveCell.Row
    rp1 = r + 1
    
'save for undo
    Dim i As Integer
    Dim u As UndoAggregationDataType
    u.oldRowIdx = r
    Set u.oldWorkbook = ActiveWorkbook
    Set u.oldSheet = ActiveSheet
    For i = 1 To 5
        u.oldLine1(i) = Range(Chr(65 + i) & r).Formula
        u.oldLine2(i) = Range(Chr(65 + i) & rp1).Formula
    Next i
    vUndoAggregationDataLength = vUndoAggregationDataLength + 1
    ReDim Preserve vUndoAggregationData(vUndoAggregationDataLength)
    vUndoAggregationData(vUndoAggregationDataLength) = u

' really perform the work
    Range("B" & r).Value = Range("B" & r).Text & "+" & Range("B" & (rp1)).Text
    Range("C" & r).Value = Range("C" & r).Value + Range("C" & (rp1)).Value
    Range("E" & r).Value = Range("E" & r).Value + Range("E" & (rp1)).Value
    Rows(rp1 & ":" & rp1).Delete Shift:=xlUp
    
     Application.OnUndo "Undo the modality aggregation", "Undo_aggregate_modality"

End Sub

Sub Undo_aggregate_modality()
'
'   Undoes the effect of the aggregate_modality macro
'
' Keyboard Shortcut:
'          Ctrl+z (only last level)
'       or Ctrl+shift+g (undo several actions)
'
'
'   Tell user if a problem occurs
    On Error GoTo Problem
    If vUndoAggregationDataLength = 0 Then GoTo Problem
    
    Application.ScreenUpdating = False
    
    Dim u As UndoAggregationDataType
    Dim i, oldRowIdxP1 As Integer
    u = vUndoAggregationData(vUndoAggregationDataLength)
    
'   Make sure the correct workbook and sheet are active
    u.oldWorkbook.Activate
    u.oldSheet.Activate
    
    Rows(u.oldRowIdx & ":" & u.oldRowIdx).Insert Shift:=xlDown
    oldRowIdxP1 = u.oldRowIdx + 1
    For i = 1 To 5
        Range(Chr(65 + i) & u.oldRowIdx).Formula = u.oldLine1(i)
        Range(Chr(65 + i) & oldRowIdxP1).Formula = u.oldLine2(i)
    Next i
    
    vUndoAggregationDataLength = vUndoAggregationDataLength - 1
    ReDim Preserve vUndoAggregationData(vUndoAggregationDataLength)
    
    Exit Sub

'   Error handler
Problem:
    MsgBox "Can't undo modality aggregation"
End Sub

