Adjust visual formatting of macro output.

The macro below produces an Output tab with data when run against any of the tabs in this workbook.  Visually, the Output tab that is created needs some cleaning up. If only one of the items below can be accomplished, then I will accept the solution immediately and ask a new question. Thank you for any assistance that can be provided in cleaning up the Output tab a little bit.

Freeze panes on the first 11 rows so that the header row will always be visible when scrolling.
Shorten the name of the Order Type column to just Order.
Rename the OT column to say Period and the data in it where M becomes Monthly spelled out, and O becomes Other spelled out.
Left justify the data in all columns except for P#, S#, L#, Qty, Strike, Days which should be centered.
Header row should always remain left justified.
Add a Total Row at the bottom that simply displays a count for the number notes that are filled in for that column, and leaves every other total empty.
Auto-fit all columns to width of data with the exception of the Notes column.
Always return focus to cell A1.

Currently the macro runs on all the tabs in the workbook and hopefully, that will still be the case when I am finished cleaning it up a little. If possible, please try not to re-post the workbook itself, but rather just the code as done below.
Option Explicit
'--> This macro takes either pm or rm tabs and creates a properly formatted table in a new tab'
'called Output with the data from the Trade History section of the original tab. It also takes'
'the notes from the Order History section of the original tab and then indexes and sorts each'
'Spread into meaningful positions.'

'Future development will include hiding the Leg and Spread numbers, as well as making some
'calculations on each overall position.'

Const AOH = "Account Order History"
Const ATH = "Account Trade History"
Const PAL = "Profits and Losses"
Const EQT = "Equities"
Const OPT = "Options"
Const OTH = "Others"
Const FRX = "Forex"

Dim wsopt As Worksheet
    

Private Sub AddMOColumn()
'This Sub will Add A new Column before Exp Column J that should indicate either of the following
'M for Monthly when the date in Exp is formated as Mmm-yy the date should be the 3rd friday of the month
'O for Weekly or Quarterly options


Dim MaxRow As Long, I As Long
Dim dDate As Date
Dim ThirdThuOfTheMonth As Date
Dim a

MaxRow = wsopt.Rows(wsopt.Rows.Count).End(xlUp).Row
wsopt.Select
Columns("J:J").Select
Selection.Insert Shift:=xlToRight
wsopt.Range("J11") = "OT"

For I = 12 To MaxRow
    If wsopt.Cells(I, "K") <> "" Then
        If wsopt.Cells(I, "K").NumberFormat = "mmm-dd-yy" Then
            wsopt.Cells(I, "J") = "O"
        Else
            wsopt.Cells(I, "J") = "M"
            dDate = wsopt.Cells(I, "K")
            dDate = DateSerial(Year(dDate), Month(dDate), 1)
            Select Case Weekday(dDate)
                Case 5  'If Date is a Thursday then add 14 days
                    ThirdThuOfTheMonth = DateValue(dDate + 14)
                Case Is > 5 'If Date is Friday or saturday then add 21+1 days
                    ThirdThuOfTheMonth = DateValue(dDate + 21 - (Weekday(dDate) - vbThursday))
                Case Is < 5 'If Date is Sunday to Thurthday then add 14+ diffrence to friday days
                    ThirdThuOfTheMonth = DateValue(dDate + 14 + vbThursday - Weekday(dDate))
            End Select
            If Weekday(ThirdThuOfTheMonth) <> vbThursday Then
                MsgBox ("this date: " & ThirdThuOfTheMonth & " does not corespond to a Thursday! on row " & I & " Please check that date in Col K is actually a valid date then re-run the whole macro.")
            End If
            wsopt.Cells(I, "K") = ThirdThuOfTheMonth
        End If
    End If
Next I
End Sub

Private Sub AddDaysandPLColumn()
'This Sub will Add 3 new Columns
'Days to Exp in Col N next to type Column which should be the diffrence in days between Exec Time and Exp
'P/L Balance Col R
'P/L% Col S


Dim MaxRow As Long, I As Long
Dim dDate As Date
Dim ThirdThuOfTheMonth As Date
Dim a

MaxRow = wsopt.Rows(wsopt.Rows.Count).End(xlUp).Row
wsopt.Select
Columns("N:N").Select
Selection.Insert Shift:=xlToRight
wsopt.Range("N11") = "Days to Exp"
Columns("R:S").Select
Selection.Insert Shift:=xlToRight
wsopt.Range("R11") = "P/L Balance"
wsopt.Range("S11") = "P/L %"


For I = 12 To MaxRow
    If wsopt.Cells(I, "K") <> "" Then
        wsopt.Cells(I, "N") = DateValue(wsopt.Cells(I, "C")) - DateValue(wsopt.Cells(I, "K"))
    End If
    
    
Next I
End Sub


Sub TradeReport()
    Dim wsPM As Worksheet
    Dim aCell As Range, bCell As Range, cCell As Range, delRange As Range
    Dim AOHRow As Long, PALRow As Long, ATHRow As Long
    Dim LastRow As Long, I As Long, J As Long
    Dim shName As String
    Dim SearchString As String, MatchString As String, init1String As String, init2String As String
    Dim intNum  As Long
    Dim FirstAddress As String
    
    On Error GoTo Whoa
    
    Application.ScreenUpdating = True
    
    Set wsPM = ActiveSheet
    
    shName = wsPM.Name
        
    '--> Make New "Output" Sheet if one already exists'
    On Error Resume Next
    Application.DisplayAlerts = False
    Set wsopt = Sheets("Output")
    intNum = 0
    While Err.Number = 0
        Err.Clear
        intNum = intNum + 1
        Set wsopt = Sheets("Output" & intNum)
    Wend
    Err.Clear
    On Error GoTo 0
    Application.DisplayAlerts = True
    
    '--> Recreate "Output" Sheet and move it to the right'
    Set wsopt = Worksheets.Add(after:=Worksheets(Worksheets.Count))
    If intNum = 0 Then
        wsopt.Name = "Output"
    Else
        wsopt.Name = "Output" & intNum
    End If
    
    '--> Find the "Account Trade History" cell in Sheet PM'
    Set aCell = wsPM.Columns(1).Find(What:=ATH, LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)
    
    '--> If "Account Trade History" is found'
    If Not aCell Is Nothing Then
        '--> Get the starting row of "Account Trade History"'
        ATHRow = aCell.Row
        
        If LCase(Left(shName, 2)) = "pm" Then
            '--> Find the "Options" cell in Sheet PM'
            Set bCell = wsPM.Columns(1).Find(What:=OPT, LookIn:=xlFormulas, _
            LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False, SearchFormat:=False)
        
            If bCell Is Nothing Then
            '--> Find the "Forex" cell in Sheet PM if Options is not found'
                Set bCell = wsPM.Columns(1).Find(What:=FRX, LookIn:=xlFormulas, _
                LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False)
            End If
            
            If bCell Is Nothing Then
            '--> Find the "Profits and Losses" cell in Sheet PM if Forex is not found'
                Set bCell = wsPM.Columns(1).Find(What:=PAL, LookIn:=xlFormulas, _
                LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False)
            End If
        End If
        
        If LCase(Left(shName, 2)) = "rm" Then
            '--> Find the "Equities" cell in Sheet RM'
            Set bCell = wsPM.Columns(1).Find(What:=EQT, LookIn:=xlFormulas, _
            LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False, SearchFormat:=False)
            
            If bCell Is Nothing Then
            '--> Find the "Others" cell in Sheet RM if Equities is not found
                Set bCell = wsPM.Columns(1).Find(What:=OTH, LookIn:=xlFormulas, _
                LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False)
            End If
        End If
        
        '--> If "Profits and Losses" is found'
        If Not bCell Is Nothing Then
            '--> Get the starting row of "Profits and Losses"
            PALRow = bCell.Row
            
            '--> Output Trade History to new tab.'
            wsPM.Rows((ATHRow + 1) & ":" & (PALRow - 1)).Copy wsopt.Rows(1)
            
            If LCase(Left(shName, 2)) = "rm" Then
                wsopt.Select
                Columns("A:A").Select
                Selection.Insert Shift:=xlToRight
            End If
            
            With wsopt
                '--> Remove last three columns because they are duplicates.'
                .Columns("M:O").Delete Shift:=xlToLeft
                
                '--> Define the notes column.'
                .Range("A1").Value = "Notes"
                .Columns("A:A").Replace What:="DEFAULT", Replacement:="", LookAt:=xlPart, _
                SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
                
                '--> Get the last row of Output Sheet'
                LastRow = .Cells.Find(What:="*", after:=[A1], SearchOrder:=xlByRows, _
                          SearchDirection:=xlPrevious).Row
                   
                '--> Unsure of what this section does?'
                Set cCell = wsPM.Columns(1).Find(What:=AOH, LookIn:=xlFormulas, _
                LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False)
                
                If Not cCell Is Nothing Then
                    AOHRow = cCell.Row + 1
                    
                '--> Copy the notes into the new notes column.
                    wsPM.Range("IV:IV").ClearContents
                    For I = AOHRow To ATHRow
                            SearchString = wsPM.Range("D" & I).Value & "###" & _
                            wsPM.Range("F" & I).Value & "###" & _
                            wsPM.Range("G" & I).Value & "###" & _
                            wsPM.Range("H" & I).Value & "###" & _
                            wsPM.Range("I" & I).Value
                            wsPM.Range("IV" & I).Value = SearchString
                    Next I
                
                    For J = 2 To LastRow
                        MatchString = .Range("D" & J).Value & "###" & _
                                        .Range("F" & J).Value & "###" & _
                                        .Range("G" & J).Value & "###" & _
                                        .Range("H" & J).Value & "###" & _
                                        .Range("I" & J).Value
                
                            Set cCell = wsPM.Range("IV:IV").Find(What:=MatchString, LookIn:=xlFormulas, _
                                        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                                        MatchCase:=False, SearchFormat:=False)
                            If Not cCell Is Nothing Then
                                FirstAddress = cCell.Address
                                    Do
                                        If wsopt.Range("F" & J).Value = wsPM.Range("F" & cCell.Row).Value Then
                                            .Range("A" & J).Value = wsPM.Range("A" & cCell.Row).Value
                                            Exit Do
                                        Else
                                            Set cCell = wsPM.Range("IV:IV").FindNext(cCell)
                                        End If
                                    Loop While Not cCell Is Nothing And cCell.Address <> FirstAddress
                            End If
                    Next J
                End If
                GoTo There

                '--> Copy the notes into the new notes column. old'
                    For I = AOHRow To ATHRow
                        SearchString = wsPM.Range("D" & I).Value & "###" & _
                        wsPM.Range("F" & I).Value & "###" & _
                        wsPM.Range("G" & I).Value & "###" & _
                        wsPM.Range("H" & I).Value & "###" & _
                        wsPM.Range("I" & I).Value
                        init1String = wsPM.Range("F" & I).Value
                                       For J = 2 To LastRow
                            init2String = wsopt.Range("F" & J).Value
                
                           If init1String = init2String Then
                                MatchString = .Range("D" & J).Value & "###" & _
                                              .Range("F" & J).Value & "###" & _
                                              .Range("G" & J).Value & "###" & _
                                              .Range("H" & J).Value & "###" & _
                                              .Range("I" & J).Value
                
                               If MatchString = SearchString Then
                                   .Range("A" & J).Value = wsPM.Range("A" & I).Value
                               End If
                          End If
                        Next J
                    Next I
                'End If
                
There:
                '--> Make the Output tab into a table that can be filtered by the column headers.'
                .ListObjects.Add(xlSrcRange, Range("$A$1:$L$" & LastRow), , xlYes).Name = "Table1"
                .ListObjects("Table1").ShowTableStyleRowStripes = False
                'ListObjects("Table1").TableStyle = "TableStyleLight1"'
                .Columns("B:L").EntireColumn.AutoFit
                
            End With
        End If
    End If
    Application.ScreenUpdating = False
    NewUpdates
    FixDate
    Indexing
    Sorting
    AddMOColumn
    AddDaysandPLColumn
    If LCase(Left(shName, 2)) = "rm" Then
        UpdateNotes wsPM, AOHRow, ATHRow
    End If
    
    wsopt.Cells(1, 1).Select

    Application.ScreenUpdating = True

'--> Clean Up and Exit.'
LetsContinue:
    Application.ScreenUpdating = True
    Set aCell = Nothing: Set bCell = Nothing: Set cCell = Nothing: Set delRange = Nothing
    On Error Resume Next
    Set wsopt = Nothing: Set wsPM = Nothing
    On Error GoTo 0
    Exit Sub
    
'--> Error Handling'
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

Private Sub FixDate()
'This Sub will go thru Exp Column Col J and will Fix the date to allow for either mm-yy or mmm-dd-yy.

Dim MaxRow As Long, I As Long
Dim tmpM As String, tmpD As String, tmpY As String

MaxRow = wsopt.Rows(wsopt.Rows.Count).End(xlUp).Row

For I = 12 To MaxRow
    '---> Strip Dates and Fix them
    If wsopt.Cells(I, "J") <> "" Then
        If IsDate(wsopt.Cells(I, "J")) Then
            '---> Format normally if normal Date format as 'mmm-dd-yy'
            wsopt.Cells(I, "J").NumberFormat = "Mmm-yy"
        Else
            '---> Strip the date in Day month Year then re-group so system would recognize
            '     it as a date and then apply format 'mmm-yy'
            tmpM = Left(wsopt.Cells(I, "J"), 3)
            tmpY = Right(wsopt.Cells(I, "J"), 2)
            tmpD = Mid(wsopt.Cells(I, "J"), 4, Len(wsopt.Cells(I, "J")) - 6)
            wsopt.Cells(I, "J") = tmpM & " " & Format(Val(tmpD), "") & ", " & Format(Val(tmpY), "")
            wsopt.Cells(I, "J").NumberFormat = "Mmm-dd-yy"
        End If
    End If

Next I

End Sub

Private Sub NewUpdates()
Dim I As Integer

'---> Create extra space at the top of the table of approximately 10 rows.
wsopt.Rows("1:10").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove

'---> Modify the date format of the Exec Time column to reflect the format of ddd mmm dd, yyyy hh:mm'
'and the Exp column to reflect the format of mm-yy.'
For I = 12 To wsopt.Cells(wsopt.Rows.Count, "K").End(xlUp).Row
wsopt.Range("B" & I).NumberFormat = "ddd mmm-dd-yyyy hh:mm"
wsopt.Range("G" & I).NumberFormat = "mmm-yy"
Next I

'--> Add Columns for Postion, Spread, and Leg Numbers'
'Add P# column before the Exec Time column with the comment "Position #" in the header for the P# column.'
'Add  S# column between the Exec Time and Spread columns with the comment "Spread #" in the header for the S# column.'
'Add L# column between the Spread and Side columns with the comment "Leg #" in the header for the L# column.'
wsopt.Columns("B:B").Insert Shift:=xlToRight
wsopt.Columns("D:D").Insert Shift:=xlToRight
wsopt.Columns("F:F").Insert Shift:=xlToRight

'---> Format column D and E to number format
wsopt.Range("D12:D" & wsopt.Cells(wsopt.Rows.Count, "K").End(xlUp).Row).NumberFormat = "0"
wsopt.Range("F12:F" & wsopt.Cells(wsopt.Rows.Count, "K").End(xlUp).Row).NumberFormat = "0"
wsopt.Range("B12:B" & wsopt.Cells(wsopt.Rows.Count, "K").End(xlUp).Row).NumberFormat = "0"

'---> Rename the header of the added Position, Spread, and Leg Number columns'
wsopt.Range("B11") = "P#": wsopt.Range("D11") = "S#": wsopt.Range("F11") = "L#"

'---> Set autofit to the width of column D and E
wsopt.Columns("D:D").EntireColumn.AutoFit
wsopt.Columns("F:F").EntireColumn.AutoFit
wsopt.Columns("B:B").EntireColumn.AutoFit
'---> Add comments
wsopt.Range("B11").AddComment
wsopt.Range("B11").Comment.Visible = False
wsopt.Range("B11").Comment.Text Text:="Position No"
wsopt.Range("D11").AddComment
wsopt.Range("D11").Comment.Visible = False
wsopt.Range("D11").Comment.Text Text:="Spread No"
wsopt.Range("F11").AddComment
wsopt.Range("F11").Comment.Visible = False
wsopt.Range("F11").Comment.Text Text:="Leg No"

'---> Shrink the printout so all column will be printed in the same page
ActiveSheet.PageSetup.PrintArea = ""
wsopt.PageSetup.FitToPagesWide = 1
wsopt.PageSetup.FitToPagesTall = 1

End Sub

'DEFINITIONS - Definitions to understand prior to Indexing and Ordering'
'1. Positions - Positions can be made up of more than one Spread and the newest Positions appear at the top of the sheet.'
'2. Spreads - Spreads can be made up of more than one Leg and their order with a position can change.'
'3. Legs - Legs are made up of individual rows within a Spread and there order within the spread never changes.'

Private Sub Indexing()
'Each Position, Spread, and Leg is indexed with a number according to the value in its Exec Date column.'
'P# - Positions are numbered sequentially with 1 being  meaning that it contains a newer Exec Date than any other positions.'
'S# - Spreads are numbered sequentially with 1 meaning that it contains the a newer Exec Date than the other spreads.'
'L# - Legs are numbered sequentially with 1 containing the oldest Exec Date within it's particular spread and starting over at the next spread.'
'If the Exec Date column (which is actually a date and time stamp) contains the same values, then the Symbol is used in alphabetical order.'

Dim I As Integer, K As Double, Z As Double, J As Double, l As Double, test As Boolean, test1 As Boolean
Dim WS As Worksheet, q As Double, Rcount As Double, x As Double, SpreadNo As Double
Sheets.Add after:=Sheets(Sheets.Count)
Set WS = Sheets(Sheets.Count)
K = 0: Z = -1: Rcount = wsopt.Cells(wsopt.Rows.Count, "K").End(xlUp).Row: SpreadNo = 0

For I = 12 To Rcount

    If K = 0 And Z = -1 Then
        K = K + 1: Z = Z + 2:
        WS.Cells(K, Z) = wsopt.Range("I" & I) & wsopt.Range("J" & I) & wsopt.Range("L" & I) & " " & wsopt.Range("K" & I)
        
        For x = I + 1 To Rcount
        If wsopt.Range("C" & x) = "" Then
            If InStr(1, WS.Cells(K, Z), wsopt.Range("K" & x)) = 0 Then WS.Cells(K, Z) = WS.Cells(K, Z) & " " & wsopt.Range("K" & x)
        Else
        Exit For
        End If
        Next x
        WS.Cells(K + 1, Z) = wsopt.Range("C" & I) & wsopt.Range("E" & I)
        WS.Cells(K + 1, Z + 1) = WS.Cells(K, Z + 1) + 1
        wsopt.Range("B" & I) = 1:  wsopt.Range("F" & I) = 1
    Else
        If J = 0 Then J = 1
        If wsopt.Range("C" & I) = "" Then
            test = True
        Else
        test = False: q = -1
    For J = 1 To Z Step 2
        q = q + 1
        If InStr(1, WS.Cells(1, J), wsopt.Range("I" & I) & wsopt.Range("J" & I) & wsopt.Range("L" & I)) > 0 Then
        If InStr(1, WS.Cells(1, J), wsopt.Range("K" & I)) > 0 Then
            wsopt.Range("B" & I) = J - q: test = True
            For x = I + 1 To Rcount
            If wsopt.Range("C" & x) = "" Then
                If InStr(1, WS.Cells(K, J), wsopt.Range("K" & x)) = 0 Then WS.Cells(K, J) = WS.Cells(K, J) & " " & wsopt.Range("K" & x)
            Else
            Exit For
            End If
            Next x
        Else
            For x = I + 1 To Rcount
            If wsopt.Range("C" & x) = "" Then
                If InStr(1, WS.Cells(K, J), wsopt.Range("K" & x)) > 0 Then wsopt.Range("B" & I) = J - q: test = True
            Else
            Exit For
            End If
            Next x
            If test = True Then
            WS.Cells(K, J) = WS.Cells(K, J) & " " & wsopt.Range("K" & I)
            For x = I + 1 To Rcount
            If wsopt.Range("C" & x) = "" Then
                If InStr(1, WS.Cells(K, J), wsopt.Range("K" & x)) = 0 Then WS.Cells(K, J) = WS.Cells(K, Z) & " " & wsopt.Range("K" & x)
            Else
            Exit For
            End If
            Next x
            End If
        End If
        
        
        If test = True Then Exit For
        End If
        Next J
        End If
    
    If test = True Then
             l = WS.Cells(WS.Rows.Count, J).End(xlUp).Row + 1
        If wsopt.Range("C" & I) = "" Then
            If J = 0 Then wsopt.Range("B" & I) = 1 Else wsopt.Range("B" & I) = J - q
            WS.Cells(l - 1, J + 1) = WS.Cells(l - 1, J + 1) + 1
            wsopt.Range("F" & I) = WS.Cells(l - 1, J + 1)
        Else
            WS.Cells(l, J) = wsopt.Range("C" & I) & wsopt.Range("E" & I)
            WS.Cells(l, J + 1) = WS.Cells(l, J + 1) + 1
            wsopt.Range("F" & I) = 1
        End If
    Else
        K = 1: Z = Z + 2: q = q + 1
        WS.Cells(K, Z) = wsopt.Range("I" & I) & wsopt.Range("J" & I) & wsopt.Range("L" & I) & " " & wsopt.Range("K" & I)
        For x = I + 1 To Rcount
        If wsopt.Range("C" & x) = "" Then
            If InStr(1, WS.Cells(K, Z), wsopt.Range("K" & x)) = 0 Then WS.Cells(K, Z) = WS.Cells(K, Z) & " " & wsopt.Range("K" & x)
        Else
        Exit For
        End If
        Next x
        WS.Cells(K + 1, Z) = wsopt.Range("C" & I) & wsopt.Range("E" & I)
        WS.Cells(K + 1, Z + 1) = WS.Cells(K, Z + 1) + 1
        wsopt.Range("B" & I) = Z - q: wsopt.Range("F" & I) = 1
    End If
    End If
Next I
Application.DisplayAlerts = False
WS.Delete
Application.DisplayAlerts = True

'---> The empty cells in the Exec Time and Spread columns should take on the information'
'of the preceding cell because they are part of the same Spread.'

For I = 12 To Rcount
    If wsopt.Range("E" & I) = "" And I > 12 Then
    wsopt.Range("E" & I) = wsopt.Range("E" & I - 1)
    wsopt.Range("C" & I) = wsopt.Range("C" & I - 1)
    wsopt.Range("C" & I & ":E" & I).Font.Color = -5395027
    End If
Next I

wsopt.Sort.SortFields.Add Key:=Range("C11"), _
        SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
        
         With ActiveSheet.Sort
        .SetRange Range("A12:O" & Rcount)
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
For I = 12 To Rcount
     If wsopt.Range("F" & I) = 1 Then
        SpreadNo = SpreadNo + 1: wsopt.Range("D" & I) = SpreadNo
     Else
     wsopt.Range("D" & I) = SpreadNo
     End If
Next I
 
End Sub

Private Sub Sorting()

'Positions can contain single or multi-legged spreads but the sort order of the legs 'within' each'
'spread never changes. This is an important point because by contrast, the sort order in which each
'spread appears within the overall position does indeed change. Here the oldest spreads should'
'appear at the top of the position while newer spreads should appear at the bottom of the position.'

Dim I As Double, Brow As Double, Erow As Double, Prow As Double
Dim Rcount As Double

'On Error Resume Next
Rcount = wsopt.Cells(wsopt.Rows.Count, "B").End(xlUp).Row

 '---> Sorting the output by the Position No.
    wsopt.Sort.SortFields.Clear
    wsopt.Sort.SortFields.Add Key:=Range("B11"), _
        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
     
    With wsopt.Sort
        .SetRange Range("A11:O" & Rcount)
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    
'--> Skipping a row between each major position
For I = Rcount To 13 Step -1
If wsopt.Range("B" & I) <> wsopt.Range("B" & I - 1) And wsopt.Range("B" & I) <> "" Then
    wsopt.Rows(I & Chr(58) & I).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    
    '--> Added by gowflow to keep correct counting of last row
    Rcount = Rcount + 1
End If
Next I

'--> Sorting the output by Date descending
Brow = 0

'--> Changed by gowflow from upper Rcount to Rcount +1
wsopt.Sort.SortFields.Add Key:=wsopt.Range("C11"), _
    SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal

For I = 12 To Rcount
If wsopt.Range("B" & I) <> "" Then
    If Brow = 0 Then
        Brow = I: Erow = I
        Else
        Erow = I
    End If
Else
        
         With wsopt.Sort
        .SetRange Range("A" & Brow & ":O" & Erow)
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    Brow = 0
wsopt.Range("A" & I - 1 & ":O" & I - 1).Copy Destination:=wsopt.Range("A" & I & ":O" & I)
wsopt.Range("A" & I & ":O" & I).Font.ThemeColor = xlThemeColorDark1
End If
Next I

wsopt.Range("P" & 12) = wsopt.Range("D" & 12): Prow = wsopt.Range("D" & 12)
For I = 13 To Rcount
If wsopt.Range("B" & I) = wsopt.Range("B" & I - 1) Then
    wsopt.Range("P" & I) = Prow
Else
    Prow = wsopt.Range("D" & I)
    wsopt.Range("P" & I) = Prow
End If
Next I

wsopt.Range("B" & 12) = 1: Prow = 1
For I = 13 To Rcount
If wsopt.Range("P" & I) = wsopt.Range("P" & I - 1) Then
    wsopt.Range("B" & I) = Prow
    If wsopt.Range("P" & I) = wsopt.Range("P" & I + 1) Then wsopt.Range("B" & I).Font.Color = -5395027
Else
    Prow = Prow + 1
    wsopt.Range("B" & I) = Prow
End If
Next I
wsopt.Columns("P:P").Delete Shift:=xlToLeft
   
End Sub

Sub UpdateNotes(WS As Worksheet, FMRow As Long, TORow As Long)
'This Sub will update noted for rm sheets from the Account Order History section in Col A
'To match with data in the Output file created under wsopt variable.

Dim MaxRow As Long, I As Long, J As Long, K As Long, Z As Long
Dim Note As String
Dim NoteItem
Dim Row As Range
Dim Status
Dim ParClose As Long, RowMatched As Long, UnMatchedNotes As Long, NoteFound As Long
Dim BkRatio As Boolean, FoundIT As Boolean
Dim STMonth As Date, ENDMonth As Date


MaxRow = wsopt.Rows(wsopt.Rows.Count).End(xlUp).Row

'---> Clean the Area F to Z to dissec Notes
WS.Range("F" & FMRow & ":ZZ" & TORow).ClearContents
WS.Range("F" & FMRow & ":ZZ" & TORow).ClearFormats


'---> Clean the notes and copy to Col F only for Status Filled Notes
For I = FMRow + 1 To TORow
    Status = Split(WS.Cells(I, "D"), " ")
    For J = 0 To UBound(Status)
        If UCase(Status(J)) = "FILLED" Then
            '---> If a note start with (Replacing ... then remove the first part till the first space
            If Left(WS.Cells(I, "C"), 10) = "(Replacing" Then
                ParClose = InStr(1, WS.Cells(I, "C"), ")")
            Else
                ParClose = 0
            End If
            
            If ParClose <> 0 Then
                WS.Cells(I, "F") = Mid(WS.Cells(I, "C"), ParClose + 2, Len(WS.Cells(I, "C")) - ParClose - 1)
            Else
                WS.Cells(I, "F") = WS.Cells(I, "C")
            End If
            Note = WS.Cells(I, "F")
            NoteItem = Split(Note, " ")
            Z = 0
            
            '---> Check to see if BACKRATIO is found then treat the sequence diffrently
            If InStr(1, WS.Cells(I, "F"), "BACKRATIO") <> 0 Then
                BkRatio = True
            Else
                BkRatio = False
            End If
            
            '---> Loop thru all items in the Note
            For K = 0 To UBound(NoteItem)
                '---> Remove any items that has open/close brakets as this is comment
                If Left(NoteItem(K), 1) = "(" Or Right(NoteItem(K), 1) = ")" Then
                    K = K + 1
                    Z = Z - 1
                End If
                
                '---> Remove any first letter / at first position
                If Left(NoteItem(K), 1) = "/" Then NoteItem(K) = Right(NoteItem(K), Len(NoteItem(K)) - 1)
                
                '---> Keep only VERTICAL/BUTTERFLY/STRANGLE/DIAGONAL in Second position
                If K = 2 Then
                    If UCase(NoteItem(K)) = "VERTICAL" Or _
                       UCase(NoteItem(K)) = "BUTTERFLY" Or _
                       UCase(NoteItem(K)) = "STRANGLE" Or _
                       UCase(NoteItem(K)) = "DIAGONAL" Then
                        Z = 0
                    Else
                        Z = 1
                    End If
                End If
                
                If BkRatio Then
                    '---> If BACKRATIO encountered then treat the sequence diffrently.
                    Select Case K
                    Case 0
                        WS.Cells(I, K + 7).NumberFormat = "@"
                        WS.Cells(I, K + 7) = Format(NoteItem(0), "@")
                    Case 1, 2
                        WS.Cells(I, 7 + 1).NumberFormat = "@"
                        WS.Cells(I, 7 + 1) = Format(NoteItem(1) & " " & NoteItem(2), "@")
                    Case Else
                        WS.Cells(I, K + 7 - 1).NumberFormat = "@"
                        WS.Cells(I, K + 7 - 1) = Format(NoteItem(K), "@")
                    End Select
                Else
                    
                    If InStr(1, Note, "@") <> 0 Then
                        '---> in any sequence is @ is encountered make sure it is positioned
                        '     in Col P as it is the Price Column the rest will follow.
                        If Left(NoteItem(K), 1) = "@" And K + 7 + Z <> 16 Then
                            Z = 16 - 7 - K
                        End If
                    Else
                        If K + 7 + Z = 16 Then
                            Z = 16 - 7 - K + 1
                        End If
                    End If
                    WS.Cells(I, K + 7 + Z).NumberFormat = "@"
                    WS.Cells(I, K + 7 + Z) = Format(NoteItem(K), "@")
                End If
            Next K
        End If
    Next J
Next I


'---> Loop Again thru all the notes in the Account Order History section
'     and match the columns where there is data to find the threads in sheet output
'     Columns in Sheet   G H I J K L M N  O  P  Q
'     Columns in Output  G H E I - [K] L  M  P  Q
'     Column Num Output  7   5 9    11 12 13 16 17
'     Columns to check   Y   Y Y    Y  Y  Y  Y  Y

For I = FMRow + 1 To TORow
    
    If WS.Cells(I, "F") <> "" Then
        wsopt.UsedRange.AutoFilter 1, Criteria1:=""
        If WS.Cells(I, "G") <> "" Then wsopt.UsedRange.AutoFilter 7, WS.Cells(I, "G")
        If WS.Cells(I, "I") <> "" Then wsopt.UsedRange.AutoFilter 5, WS.Cells(I, "I")
        If WS.Cells(I, "J") <> "" Then wsopt.UsedRange.AutoFilter 9, WS.Cells(I, "J")
        If WS.Cells(I, "L") <> "" Then
            If Len(WS.Cells(I, "L")) = 3 Then
                On Error Resume Next
                STMonth = DateSerial(WS.Cells(I, "M"), Month(DateValue(WS.Cells(I, "L") & " 1," & Year(Now))), 1)
                ENDMonth = DateSerial(Year(STMonth), Month(STMonth), Day(Application.WorksheetFunction.EoMonth(STMonth, 0)))
                wsopt.UsedRange.AutoFilter 11, Criteria1:=">=" & STMonth, Operator:=xlAnd, Criteria2:="<=" & ENDMonth
            Else
                On Error Resume Next
                STMonth = DateValue(Left(WS.Cells(I, "L"), 3) & " " & Right(WS.Cells(I, "L"), Len(WS.Cells(I, "L")) - 3) & "," & WS.Cells(I, "M"))
                wsopt.UsedRange.AutoFilter 11, Criteria1:=">=" & STMonth, Operator:=xlAnd, Criteria2:="<=" & STMonth
            End If
        End If
        On Error GoTo 0
        If WS.Cells(I, "N") <> "" And InStr(1, WS.Cells(I, "N"), "/") = 0 Then wsopt.UsedRange.AutoFilter 12, WS.Cells(I, "N")
        If WS.Cells(I, "O") <> "" And InStr(1, WS.Cells(I, "N"), "/") = 0 Then wsopt.UsedRange.AutoFilter 13, WS.Cells(I, "O")
        'If WS.Cells(I, "P") <> "" Then wsopt.UsedRange.AutoFilter 16, Criteria1:="<=" & Val(Right(WS.Cells(I, "P"), Len(WS.Cells(I, "P")) - 1))
        If WS.Cells(I, "Q") <> "" Then wsopt.UsedRange.AutoFilter 17, WS.Cells(I, "Q")
        NoteFound = NoteFound + 1
        FoundIT = True
        
        For Each Row In wsopt.Range("11:" & MaxRow).EntireRow.SpecialCells(xlCellTypeVisible).Rows
            If wsopt.Cells(Row.Row, "A").EntireRow.Hidden = False And wsopt.Cells(Row.Row, "C") <> "" And Row.Row <> 11 Then
                wsopt.Cells(Row.Row, "A") = WS.Cells(I, "F")
                RowMatched = RowMatched + 1
                FoundIT = False
                Exit For
            End If
        Next Row
        
        If FoundIT Then
            'MsgBox (WS.Cells(I, "F") & Chr(10) & "Was not mached in sheet Output !")
            WS.Cells(I, "F").Interior.ColorIndex = 3
            UnMatchedNotes = UnMatchedNotes + 1
        End If
        
        '---> Clear All Filters
        wsopt.UsedRange.AutoFilter 1
        wsopt.UsedRange.AutoFilter 5
        wsopt.UsedRange.AutoFilter 7
        wsopt.UsedRange.AutoFilter 9
        wsopt.UsedRange.AutoFilter 11
        wsopt.UsedRange.AutoFilter 12
        wsopt.UsedRange.AutoFilter 13
        wsopt.UsedRange.AutoFilter 16
        wsopt.UsedRange.AutoFilter 17
    End If
Next I

MsgBox ("A total of " & RowMatched & " Spread items were matched with notes." & Chr(10) _
& "A total of " & NoteFound & " Notes FILLED were found in the Order History Section." & Chr(10) _
& "A total of " & UnMatchedNotes & " Notes were not Matched in Sheet Output.")

End Sub

Open in new window

rtod2Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

dlmilleCommented:
Here's #1: >>Freeze panes on the first 11 rows so that the header row will always be visible when scrolling.

Activate the sheet
select the intersection where you want the panes to be frozen
use these commands:
ActiveWindow.FreezePanes = FALSE
ActiveWindow.FreezePanes = TRUE

Your code is not complete as I can't see which variable is assigned to the output tab.  Nor can I tell which routine in the list of routines is the one you want to affect all these changes.  Hence, a new sub you can call from whereever you want to start this clean up process:

 
Sub cleanOutput()

    ThisWorkbook.Activate 'just in case another workbook is on top
    Set wsopt = ThisWorkbook.Sheets("Output")
    wsopt.Activate 'just in case another worksheet is in focus
    wsopt.Range("12:12").Select
    ActiveWindow.FreezePanes = False
    ActiveWindow.FreezePanes = True
    
End Sub

Open in new window


Enjoy!

Dave
0
rtod2Author Commented:
Hmm unsure how to resolve the "incomplete" issue.  I think I'll try to draw the attention of gowflow.
0
dlmilleCommented:
Here's a few more:

 
Sub cleanOutput()
Dim r As Range
Dim lastRow As Long

    'Freeze panes on the first 11 rows so that the header row will always be visible when scrolling.

    ThisWorkbook.Activate 'just in case another workbook is on top
    Set wsopt = ThisWorkbook.Sheets("Output")
    wsopt.Activate 'just in case another worksheet is in focus
    wsopt.Range("12:12").Select
    ActiveWindow.FreezePanes = False
    ActiveWindow.FreezePanes = True
    
    'Shorten the name of the Order Type column to just Order.
    
    wsopt.Range("Q11").Value = "Order"
    
    'Rename the OT column to say Period and the data in it where M becomes Monthly spelled out, and O becomes Other spelled out.
    
    wsopt.Range("J11").Value = "Period"
    
    lastRow = wsopt.Range("A" & wsopt.Rows.Count).End(xlUp).Row
    Set r = wsopt.Range(wsopt.Range("J12"), wsopt.Cells(lastRow, "J"))
    
    'in case none found, turn on error trap
    On Error Resume Next
    r.Replace what:="M", replacement:="Monthly", lookAt:=xlWhole
    r.Replace what:="O", replacement:="Other", lookAt:=xlWhole
    On Error GoTo 0
    
    'Left justify the data in all columns except for P#, S#, L#, Qty, Strike, Days which should be centered.
    
    'first make all left justified
    Set r = wsopt.Range(wsopt.Range("A12"), wsopt.Cells(lastRow, "S"))
    With r
        .HorizontalAlignment = xlLeft
        .VerticalAlignment = xlBottom
    End With
    
    'now make particular columns centered
    Set r = Union(wsopt.Range("H12:H" & lastRow), wsopt.Range("L12:L" & lastRow), wsopt.Range("N12:N" & lastRow), wsopt.Range("P12:P" & lastRow), wsopt.Range("S12:S" & lastRow))
    With r
        .HorizontalAlignment = xlCenter
    End With
    'Header row should always remain left justified.
    'Add a Total Row at the bottom that simply displays a count for the number notes that are filled in for that column, and leaves every other total empty.
    'Auto-fit all columns to width of data with the exception of the Notes column.
    'Always return focus to cell A1.


End Sub

Open in new window


Dave
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

dlmilleCommented:
>> Hmm unsure how to resolve the "incomplete" issue.  I think I'll try to draw the attention of gowflow.

Please clarify what this means.
0
rtod2Author Commented:
Can you implement it into my code?
0
dlmilleCommented:
Anythings possible.  However, is your code complete?  When I download your file and try to run a sub, I get errors because you haven't assigned wsopt to anything.  You haven't addressed the issues I teed up with that or confirmed my assumption.  Is wsopt supposed to be the Output tab or not?

Dave
0
dlmilleCommented:
You also havent' advised which routine you'd like to do this in.  I don't know what sequence you're running them in, etc.

Did you write this code?  If not, I can dig through it to figure it out, but if you did you need to provide a bit more information as to where YOU want this to be done, or at least the sequence of events that result in the last step.
0
rtod2Author Commented:
Dave, Thank you sir!

Please accept my apologies for not being better informed myself. Gowflow has been helping with it and did much of the writing. We have tried to annotate the code to the best extent possible along the way but even some of that could be wrong.

I'm afraid I don't know what wsopt is or what is supposed to happen.  What I can tell you is that after the macro is run, the Output is the result off processing whatever tab was selected when it was run. It is the visual formatting of that Output tab that needs to be included in the processing.

I'm afraid that is all I know. That said, gowflow did just answer a question of mine pertaining to the Order in which things are processed at the bottom of this thread >> http://www.experts-exchange.com/Software/Office_Productivity/Office_Suites/MS_Office/Excel/Q_27524056.html
0
dlmilleCommented:
that's useful.  Give me a moment
0
rtod2Author Commented:
Anything you can do to provide additional comments for things that might not be clear would be helpful as well.  Thank you for your help sir. It is definitely appreciated!
0
dlmilleCommented:
I think I've gone above scope for this question - met the expectation of the OP question, with all the items completed - then modifications of some of the other code and creating a new routine to tie it together....  

However, there remain unanswered questions only goflow perhaps needs to answer.  See the

runAllInOrder()

subroutine I created which runs this stuff in sequence, though i've commented out a couple lines which, perhaps, an additional question related to the one you asked goflow so he can attack this.

here's the solution:
Option Explicit
'--> This macro takes either pm or rm tabs and creates a properly formatted table in a new tab'
'called Output with the data from the Trade History section of the original tab. It also takes'
'the notes from the Order History section of the original tab and then indexes and sorts each'
'Spread into meaningful positions.'

'Future development will include hiding the Leg and Spread numbers, as well as making some
'calculations on each overall position.'

Const AOH = "Account Order History"
Const ATH = "Account Trade History"
Const PAL = "Profits and Losses"
Const EQT = "Equities"
Const OPT = "Options"
Const OTH = "Others"
Const FRX = "Forex"

Dim wsopt As Worksheet
    
Private Sub runAllInOrder()
    Set wsopt = ThisWorkbook.Sheets("Output")
    Call NewUpdates 'note modified to clean the output sheet before creating new output
    Call FixDate
    Call Indexing
    Call Sorting
    Call AddMOColumn
    Call AddDaysandPLColumn
    'If LCase(Left(shName, 2)) = "rm" Then  'where is shName defined? goflow may need to finalize
    '    UpdateNotes wsPM, AOHRow, ATHRow 'where are these defined? goflow may need to finalize
    'End If
    Call cleanOutput 'dlmille's added code for this E-E Question
End Sub


Private Sub AddMOColumn()
'This Sub will Add A new Column before Exp Column J that should indicate either of the following
'M for Monthly when the date in Exp is formated as Mmm-yy the date should be the 3rd friday of the month
'O for Weekly or Quarterly options


Dim MaxRow As Long, I As Long
Dim dDate As Date
Dim ThirdThuOfTheMonth As Date
Dim a

MaxRow = wsopt.Rows(wsopt.Rows.Count).End(xlUp).Row
wsopt.Select
Columns("J:J").Select
Selection.Insert Shift:=xlToRight
wsopt.Range("J11") = "OT"

For I = 12 To MaxRow
    If wsopt.Cells(I, "K") <> "" Then
        If wsopt.Cells(I, "K").NumberFormat = "mmm-dd-yy" Then
            wsopt.Cells(I, "J") = "O"
        Else
            wsopt.Cells(I, "J") = "M"
            dDate = wsopt.Cells(I, "K")
            dDate = DateSerial(Year(dDate), Month(dDate), 1)
            Select Case Weekday(dDate)
                Case 5  'If Date is a Thursday then add 14 days
                    ThirdThuOfTheMonth = DateValue(dDate + 14)
                Case Is > 5 'If Date is Friday or saturday then add 21+1 days
                    ThirdThuOfTheMonth = DateValue(dDate + 21 - (Weekday(dDate) - vbThursday))
                Case Is < 5 'If Date is Sunday to Thurthday then add 14+ diffrence to friday days
                    ThirdThuOfTheMonth = DateValue(dDate + 14 + vbThursday - Weekday(dDate))
            End Select
            If Weekday(ThirdThuOfTheMonth) <> vbThursday Then
                MsgBox ("this date: " & ThirdThuOfTheMonth & " does not corespond to a Thursday! on row " & I & " Please check that date in Col K is actually a valid date then re-run the whole macro.")
            End If
            wsopt.Cells(I, "K") = ThirdThuOfTheMonth
        End If
    End If
Next I
End Sub

Private Sub AddDaysandPLColumn()
'This Sub will Add 3 new Columns
'Days to Exp in Col N next to type Column which should be the diffrence in days between Exec Time and Exp
'P/L Balance Col R
'P/L% Col S


Dim MaxRow As Long, I As Long
Dim dDate As Date
Dim ThirdThuOfTheMonth As Date
Dim a

MaxRow = wsopt.Rows(wsopt.Rows.Count).End(xlUp).Row
wsopt.Select
Columns("N:N").Select
Selection.Insert Shift:=xlToRight
wsopt.Range("N11") = "Days to Exp"
Columns("R:S").Select
Selection.Insert Shift:=xlToRight
wsopt.Range("R11") = "P/L Balance"
wsopt.Range("S11") = "P/L %"


For I = 12 To MaxRow
    If wsopt.Cells(I, "K") <> "" Then
        wsopt.Cells(I, "N") = DateValue(wsopt.Cells(I, "C")) - DateValue(wsopt.Cells(I, "K"))
    End If
    
    
Next I
End Sub

Private Sub FixDate()
'This Sub will go thru Exp Column Col J and will Fix the date to allow for either mm-yy or mmm-dd-yy.

Dim MaxRow As Long, I As Long
Dim tmpM As String, tmpD As String, tmpY As String

MaxRow = wsopt.Rows(wsopt.Rows.Count).End(xlUp).Row

For I = 12 To MaxRow
    '---> Strip Dates and Fix them
    If wsopt.Cells(I, "J") <> "" Then
        If IsDate(wsopt.Cells(I, "J")) Then
            '---> Format normally if normal Date format as 'mmm-dd-yy'
            wsopt.Cells(I, "J").NumberFormat = "Mmm-yy"
        Else
            '---> Strip the date in Day month Year then re-group so system would recognize
            '     it as a date and then apply format 'mmm-yy'
            tmpM = Left(wsopt.Cells(I, "J"), 3)
            tmpY = Right(wsopt.Cells(I, "J"), 2)
            tmpD = Mid(wsopt.Cells(I, "J"), 4, Len(wsopt.Cells(I, "J")) - 6)
            wsopt.Cells(I, "J") = tmpM & " " & Format(Val(tmpD), "") & ", " & Format(Val(tmpY), "")
            wsopt.Cells(I, "J").NumberFormat = "Mmm-dd-yy"
        End If
    End If

Next I

End Sub

Private Sub NewUpdates()
Dim I As Integer

wsopt.Cells.Clear 'dlmille - clean the output tab before starting

'---> Create extra space at the top of the table of approximately 10 rows.
wsopt.Rows("1:10").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove

'---> Modify the date format of the Exec Time column to reflect the format of ddd mmm dd, yyyy hh:mm'
'and the Exp column to reflect the format of mm-yy.'
For I = 12 To wsopt.Cells(wsopt.Rows.Count, "K").End(xlUp).Row
wsopt.Range("B" & I).NumberFormat = "ddd mmm-dd-yyyy hh:mm"
wsopt.Range("G" & I).NumberFormat = "mmm-yy"
Next I

'--> Add Columns for Postion, Spread, and Leg Numbers'
'Add P# column before the Exec Time column with the comment "Position #" in the header for the P# column.'
'Add  S# column between the Exec Time and Spread columns with the comment "Spread #" in the header for the S# column.'
'Add L# column between the Spread and Side columns with the comment "Leg #" in the header for the L# column.'
wsopt.Columns("B:B").Insert Shift:=xlToRight
wsopt.Columns("D:D").Insert Shift:=xlToRight
wsopt.Columns("F:F").Insert Shift:=xlToRight

'---> Format column D and E to number format
wsopt.Range("D12:D" & wsopt.Cells(wsopt.Rows.Count, "K").End(xlUp).Row).NumberFormat = "0"
wsopt.Range("F12:F" & wsopt.Cells(wsopt.Rows.Count, "K").End(xlUp).Row).NumberFormat = "0"
wsopt.Range("B12:B" & wsopt.Cells(wsopt.Rows.Count, "K").End(xlUp).Row).NumberFormat = "0"

'---> Rename the header of the added Position, Spread, and Leg Number columns'
wsopt.Range("B11") = "P#": wsopt.Range("D11") = "S#": wsopt.Range("F11") = "L#"

'---> Set autofit to the width of column D and E
wsopt.Columns("D:D").EntireColumn.AutoFit
wsopt.Columns("F:F").EntireColumn.AutoFit
wsopt.Columns("B:B").EntireColumn.AutoFit
'---> Add comments
wsopt.Range("B11").AddComment
wsopt.Range("B11").Comment.Visible = False
wsopt.Range("B11").Comment.Text Text:="Position No"
wsopt.Range("D11").AddComment
wsopt.Range("D11").Comment.Visible = False
wsopt.Range("D11").Comment.Text Text:="Spread No"
wsopt.Range("F11").AddComment
wsopt.Range("F11").Comment.Visible = False
wsopt.Range("F11").Comment.Text Text:="Leg No"

'---> Shrink the printout so all column will be printed in the same page
ActiveSheet.PageSetup.PrintArea = ""
wsopt.PageSetup.FitToPagesWide = 1
wsopt.PageSetup.FitToPagesTall = 1

End Sub

'DEFINITIONS - Definitions to understand prior to Indexing and Ordering'
'1. Positions - Positions can be made up of more than one Spread and the newest Positions appear at the top of the sheet.'
'2. Spreads - Spreads can be made up of more than one Leg and their order with a position can change.'
'3. Legs - Legs are made up of individual rows within a Spread and there order within the spread never changes.'

Private Sub Indexing()
'Each Position, Spread, and Leg is indexed with a number according to the value in its Exec Date column.'
'P# - Positions are numbered sequentially with 1 being  meaning that it contains a newer Exec Date than any other positions.'
'S# - Spreads are numbered sequentially with 1 meaning that it contains the a newer Exec Date than the other spreads.'
'L# - Legs are numbered sequentially with 1 containing the oldest Exec Date within it's particular spread and starting over at the next spread.'
'If the Exec Date column (which is actually a date and time stamp) contains the same values, then the Symbol is used in alphabetical order.'

Dim I As Integer, K As Double, Z As Double, J As Double, l As Double, test As Boolean, test1 As Boolean
Dim WS As Worksheet, q As Double, Rcount As Double, x As Double, SpreadNo As Double
Sheets.Add after:=Sheets(Sheets.Count)
Set WS = Sheets(Sheets.Count)
K = 0: Z = -1: Rcount = wsopt.Cells(wsopt.Rows.Count, "K").End(xlUp).Row: SpreadNo = 0

For I = 12 To Rcount

    If K = 0 And Z = -1 Then
        K = K + 1: Z = Z + 2:
        WS.Cells(K, Z) = wsopt.Range("I" & I) & wsopt.Range("J" & I) & wsopt.Range("L" & I) & " " & wsopt.Range("K" & I)
        
        For x = I + 1 To Rcount
        If wsopt.Range("C" & x) = "" Then
            If InStr(1, WS.Cells(K, Z), wsopt.Range("K" & x)) = 0 Then WS.Cells(K, Z) = WS.Cells(K, Z) & " " & wsopt.Range("K" & x)
        Else
        Exit For
        End If
        Next x
        WS.Cells(K + 1, Z) = wsopt.Range("C" & I) & wsopt.Range("E" & I)
        WS.Cells(K + 1, Z + 1) = WS.Cells(K, Z + 1) + 1
        wsopt.Range("B" & I) = 1:  wsopt.Range("F" & I) = 1
    Else
        If J = 0 Then J = 1
        If wsopt.Range("C" & I) = "" Then
            test = True
        Else
        test = False: q = -1
    For J = 1 To Z Step 2
        q = q + 1
        If InStr(1, WS.Cells(1, J), wsopt.Range("I" & I) & wsopt.Range("J" & I) & wsopt.Range("L" & I)) > 0 Then
        If InStr(1, WS.Cells(1, J), wsopt.Range("K" & I)) > 0 Then
            wsopt.Range("B" & I) = J - q: test = True
            For x = I + 1 To Rcount
            If wsopt.Range("C" & x) = "" Then
                If InStr(1, WS.Cells(K, J), wsopt.Range("K" & x)) = 0 Then WS.Cells(K, J) = WS.Cells(K, J) & " " & wsopt.Range("K" & x)
            Else
            Exit For
            End If
            Next x
        Else
            For x = I + 1 To Rcount
            If wsopt.Range("C" & x) = "" Then
                If InStr(1, WS.Cells(K, J), wsopt.Range("K" & x)) > 0 Then wsopt.Range("B" & I) = J - q: test = True
            Else
            Exit For
            End If
            Next x
            If test = True Then
            WS.Cells(K, J) = WS.Cells(K, J) & " " & wsopt.Range("K" & I)
            For x = I + 1 To Rcount
            If wsopt.Range("C" & x) = "" Then
                If InStr(1, WS.Cells(K, J), wsopt.Range("K" & x)) = 0 Then WS.Cells(K, J) = WS.Cells(K, Z) & " " & wsopt.Range("K" & x)
            Else
            Exit For
            End If
            Next x
            End If
        End If
        
        
        If test = True Then Exit For
        End If
        Next J
        End If
    
    If test = True Then
             l = WS.Cells(WS.Rows.Count, J).End(xlUp).Row + 1
        If wsopt.Range("C" & I) = "" Then
            If J = 0 Then wsopt.Range("B" & I) = 1 Else wsopt.Range("B" & I) = J - q
            WS.Cells(l - 1, J + 1) = WS.Cells(l - 1, J + 1) + 1
            wsopt.Range("F" & I) = WS.Cells(l - 1, J + 1)
        Else
            WS.Cells(l, J) = wsopt.Range("C" & I) & wsopt.Range("E" & I)
            WS.Cells(l, J + 1) = WS.Cells(l, J + 1) + 1
            wsopt.Range("F" & I) = 1
        End If
    Else
        K = 1: Z = Z + 2: q = q + 1
        WS.Cells(K, Z) = wsopt.Range("I" & I) & wsopt.Range("J" & I) & wsopt.Range("L" & I) & " " & wsopt.Range("K" & I)
        For x = I + 1 To Rcount
        If wsopt.Range("C" & x) = "" Then
            If InStr(1, WS.Cells(K, Z), wsopt.Range("K" & x)) = 0 Then WS.Cells(K, Z) = WS.Cells(K, Z) & " " & wsopt.Range("K" & x)
        Else
        Exit For
        End If
        Next x
        WS.Cells(K + 1, Z) = wsopt.Range("C" & I) & wsopt.Range("E" & I)
        WS.Cells(K + 1, Z + 1) = WS.Cells(K, Z + 1) + 1
        wsopt.Range("B" & I) = Z - q: wsopt.Range("F" & I) = 1
    End If
    End If
Next I
Application.DisplayAlerts = False
WS.Delete
Application.DisplayAlerts = True

'---> The empty cells in the Exec Time and Spread columns should take on the information'
'of the preceding cell because they are part of the same Spread.'

For I = 12 To Rcount
    If wsopt.Range("E" & I) = "" And I > 12 Then
    wsopt.Range("E" & I) = wsopt.Range("E" & I - 1)
    wsopt.Range("C" & I) = wsopt.Range("C" & I - 1)
    wsopt.Range("C" & I & ":E" & I).Font.Color = -5395027
    End If
Next I

wsopt.Sort.SortFields.Add Key:=Range("C11"), _
        SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
        
         With ActiveSheet.Sort
        .SetRange Range("A12:O" & Rcount)
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
For I = 12 To Rcount
     If wsopt.Range("F" & I) = 1 Then
        SpreadNo = SpreadNo + 1: wsopt.Range("D" & I) = SpreadNo
     Else
     wsopt.Range("D" & I) = SpreadNo
     End If
Next I
 
End Sub

Private Sub Sorting()

'Positions can contain single or multi-legged spreads but the sort order of the legs 'within' each'
'spread never changes. This is an important point because by contrast, the sort order in which each
'spread appears within the overall position does indeed change. Here the oldest spreads should'
'appear at the top of the position while newer spreads should appear at the bottom of the position.'

Dim I As Double, Brow As Double, Erow As Double, Prow As Double
Dim Rcount As Double

'On Error Resume Next
Rcount = wsopt.Cells(wsopt.Rows.Count, "B").End(xlUp).Row

 '---> Sorting the output by the Position No.
    wsopt.Sort.SortFields.Clear
    wsopt.Sort.SortFields.Add Key:=Range("B11"), _
        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
     
    With wsopt.Sort
        .SetRange Range("A11:O" & Rcount)
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    
'--> Skipping a row between each major position
For I = Rcount To 13 Step -1
If wsopt.Range("B" & I) <> wsopt.Range("B" & I - 1) And wsopt.Range("B" & I) <> "" Then
    wsopt.Rows(I & Chr(58) & I).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    
    '--> Added by gowflow to keep correct counting of last row
    Rcount = Rcount + 1
End If
Next I

'--> Sorting the output by Date descending
Brow = 0

'--> Changed by gowflow from upper Rcount to Rcount +1
wsopt.Sort.SortFields.Add Key:=wsopt.Range("C11"), _
    SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal

For I = 12 To Rcount
If wsopt.Range("B" & I) <> "" Then
    If Brow = 0 Then
        Brow = I: Erow = I
        Else
        Erow = I
    End If
Else
        
         With wsopt.Sort
        .SetRange Range("A" & Brow & ":O" & Erow)
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    Brow = 0
wsopt.Range("A" & I - 1 & ":O" & I - 1).Copy Destination:=wsopt.Range("A" & I & ":O" & I)
wsopt.Range("A" & I & ":O" & I).Font.ThemeColor = xlThemeColorDark1
End If
Next I

wsopt.Range("P" & 12) = wsopt.Range("D" & 12): Prow = wsopt.Range("D" & 12)
For I = 13 To Rcount
If wsopt.Range("B" & I) = wsopt.Range("B" & I - 1) Then
    wsopt.Range("P" & I) = Prow
Else
    Prow = wsopt.Range("D" & I)
    wsopt.Range("P" & I) = Prow
End If
Next I

wsopt.Range("B" & 12) = 1: Prow = 1
For I = 13 To Rcount
If wsopt.Range("P" & I) = wsopt.Range("P" & I - 1) Then
    wsopt.Range("B" & I) = Prow
    If wsopt.Range("P" & I) = wsopt.Range("P" & I + 1) Then wsopt.Range("B" & I).Font.Color = -5395027
Else
    Prow = Prow + 1
    wsopt.Range("B" & I) = Prow
End If
Next I
wsopt.Columns("P:P").Delete Shift:=xlToLeft
   
End Sub

Sub UpdateNotes(WS As Worksheet, FMRow As Long, TORow As Long)
'This Sub will update noted for rm sheets from the Account Order History section in Col A
'To match with data in the Output file created under wsopt variable.

Dim MaxRow As Long, I As Long, J As Long, K As Long, Z As Long
Dim Note As String
Dim NoteItem
Dim Row As Range
Dim Status
Dim ParClose As Long, RowMatched As Long, UnMatchedNotes As Long, NoteFound As Long
Dim BkRatio As Boolean, FoundIT As Boolean
Dim STMonth As Date, ENDMonth As Date


MaxRow = wsopt.Rows(wsopt.Rows.Count).End(xlUp).Row

'---> Clean the Area F to Z to dissec Notes
WS.Range("F" & FMRow & ":ZZ" & TORow).ClearContents
WS.Range("F" & FMRow & ":ZZ" & TORow).ClearFormats


'---> Clean the notes and copy to Col F only for Status Filled Notes
For I = FMRow + 1 To TORow
    Status = Split(WS.Cells(I, "D"), " ")
    For J = 0 To UBound(Status)
        If UCase(Status(J)) = "FILLED" Then
            '---> If a note start with (Replacing ... then remove the first part till the first space
            If Left(WS.Cells(I, "C"), 10) = "(Replacing" Then
                ParClose = InStr(1, WS.Cells(I, "C"), ")")
            Else
                ParClose = 0
            End If
            
            If ParClose <> 0 Then
                WS.Cells(I, "F") = Mid(WS.Cells(I, "C"), ParClose + 2, Len(WS.Cells(I, "C")) - ParClose - 1)
            Else
                WS.Cells(I, "F") = WS.Cells(I, "C")
            End If
            Note = WS.Cells(I, "F")
            NoteItem = Split(Note, " ")
            Z = 0
            
            '---> Check to see if BACKRATIO is found then treat the sequence diffrently
            If InStr(1, WS.Cells(I, "F"), "BACKRATIO") <> 0 Then
                BkRatio = True
            Else
                BkRatio = False
            End If
            
            '---> Loop thru all items in the Note
            For K = 0 To UBound(NoteItem)
                '---> Remove any items that has open/close brakets as this is comment
                If Left(NoteItem(K), 1) = "(" Or Right(NoteItem(K), 1) = ")" Then
                    K = K + 1
                    Z = Z - 1
                End If
                
                '---> Remove any first letter / at first position
                If Left(NoteItem(K), 1) = "/" Then NoteItem(K) = Right(NoteItem(K), Len(NoteItem(K)) - 1)
                
                '---> Keep only VERTICAL/BUTTERFLY/STRANGLE/DIAGONAL in Second position
                If K = 2 Then
                    If UCase(NoteItem(K)) = "VERTICAL" Or _
                       UCase(NoteItem(K)) = "BUTTERFLY" Or _
                       UCase(NoteItem(K)) = "STRANGLE" Or _
                       UCase(NoteItem(K)) = "DIAGONAL" Then
                        Z = 0
                    Else
                        Z = 1
                    End If
                End If
                
                If BkRatio Then
                    '---> If BACKRATIO encountered then treat the sequence diffrently.
                    Select Case K
                    Case 0
                        WS.Cells(I, K + 7).NumberFormat = "@"
                        WS.Cells(I, K + 7) = Format(NoteItem(0), "@")
                    Case 1, 2
                        WS.Cells(I, 7 + 1).NumberFormat = "@"
                        WS.Cells(I, 7 + 1) = Format(NoteItem(1) & " " & NoteItem(2), "@")
                    Case Else
                        WS.Cells(I, K + 7 - 1).NumberFormat = "@"
                        WS.Cells(I, K + 7 - 1) = Format(NoteItem(K), "@")
                    End Select
                Else
                    
                    If InStr(1, Note, "@") <> 0 Then
                        '---> in any sequence is @ is encountered make sure it is positioned
                        '     in Col P as it is the Price Column the rest will follow.
                        If Left(NoteItem(K), 1) = "@" And K + 7 + Z <> 16 Then
                            Z = 16 - 7 - K
                        End If
                    Else
                        If K + 7 + Z = 16 Then
                            Z = 16 - 7 - K + 1
                        End If
                    End If
                    WS.Cells(I, K + 7 + Z).NumberFormat = "@"
                    WS.Cells(I, K + 7 + Z) = Format(NoteItem(K), "@")
                End If
            Next K
        End If
    Next J
Next I


'---> Loop Again thru all the notes in the Account Order History section
'     and match the columns where there is data to find the threads in sheet output
'     Columns in Sheet   G H I J K L M N  O  P  Q
'     Columns in Output  G H E I - [K] L  M  P  Q
'     Column Num Output  7   5 9    11 12 13 16 17
'     Columns to check   Y   Y Y    Y  Y  Y  Y  Y

For I = FMRow + 1 To TORow
    
    If WS.Cells(I, "F") <> "" Then
        wsopt.UsedRange.AutoFilter 1, Criteria1:=""
        If WS.Cells(I, "G") <> "" Then wsopt.UsedRange.AutoFilter 7, WS.Cells(I, "G")
        If WS.Cells(I, "I") <> "" Then wsopt.UsedRange.AutoFilter 5, WS.Cells(I, "I")
        If WS.Cells(I, "J") <> "" Then wsopt.UsedRange.AutoFilter 9, WS.Cells(I, "J")
        If WS.Cells(I, "L") <> "" Then
            If Len(WS.Cells(I, "L")) = 3 Then
                On Error Resume Next
                STMonth = DateSerial(WS.Cells(I, "M"), Month(DateValue(WS.Cells(I, "L") & " 1," & Year(Now))), 1)
                ENDMonth = DateSerial(Year(STMonth), Month(STMonth), Day(Application.WorksheetFunction.EoMonth(STMonth, 0)))
                wsopt.UsedRange.AutoFilter 11, Criteria1:=">=" & STMonth, Operator:=xlAnd, Criteria2:="<=" & ENDMonth
            Else
                On Error Resume Next
                STMonth = DateValue(Left(WS.Cells(I, "L"), 3) & " " & Right(WS.Cells(I, "L"), Len(WS.Cells(I, "L")) - 3) & "," & WS.Cells(I, "M"))
                wsopt.UsedRange.AutoFilter 11, Criteria1:=">=" & STMonth, Operator:=xlAnd, Criteria2:="<=" & STMonth
            End If
        End If
        On Error GoTo 0
        If WS.Cells(I, "N") <> "" And InStr(1, WS.Cells(I, "N"), "/") = 0 Then wsopt.UsedRange.AutoFilter 12, WS.Cells(I, "N")
        If WS.Cells(I, "O") <> "" And InStr(1, WS.Cells(I, "N"), "/") = 0 Then wsopt.UsedRange.AutoFilter 13, WS.Cells(I, "O")
        'If WS.Cells(I, "P") <> "" Then wsopt.UsedRange.AutoFilter 16, Criteria1:="<=" & Val(Right(WS.Cells(I, "P"), Len(WS.Cells(I, "P")) - 1))
        If WS.Cells(I, "Q") <> "" Then wsopt.UsedRange.AutoFilter 17, WS.Cells(I, "Q")
        NoteFound = NoteFound + 1
        FoundIT = True
        
        For Each Row In wsopt.Range("11:" & MaxRow).EntireRow.SpecialCells(xlCellTypeVisible).Rows
            If wsopt.Cells(Row.Row, "A").EntireRow.Hidden = False And wsopt.Cells(Row.Row, "C") <> "" And Row.Row <> 11 Then
                wsopt.Cells(Row.Row, "A") = WS.Cells(I, "F")
                RowMatched = RowMatched + 1
                FoundIT = False
                Exit For
            End If
        Next Row
        
        If FoundIT Then
            'MsgBox (WS.Cells(I, "F") & Chr(10) & "Was not mached in sheet Output !")
            WS.Cells(I, "F").Interior.ColorIndex = 3
            UnMatchedNotes = UnMatchedNotes + 1
        End If
        
        '---> Clear All Filters
        wsopt.UsedRange.AutoFilter 1
        wsopt.UsedRange.AutoFilter 5
        wsopt.UsedRange.AutoFilter 7
        wsopt.UsedRange.AutoFilter 9
        wsopt.UsedRange.AutoFilter 11
        wsopt.UsedRange.AutoFilter 12
        wsopt.UsedRange.AutoFilter 13
        wsopt.UsedRange.AutoFilter 16
        wsopt.UsedRange.AutoFilter 17
    End If
Next I

MsgBox ("A total of " & RowMatched & " Spread items were matched with notes." & Chr(10) _
& "A total of " & NoteFound & " Notes FILLED were found in the Order History Section." & Chr(10) _
& "A total of " & UnMatchedNotes & " Notes were not Matched in Sheet Output.")

End Sub

Sub cleanOutput()
Dim r As Range, rng As Range
Dim lastRow As Long

    'assumes output tab just generated and thus doesn't have total row already, etc., as it had been previously cleared...
    
    'Freeze panes on the first 11 rows so that the header row will always be visible when scrolling.

    ThisWorkbook.Activate 'just in case another workbook is on top

    wsopt.Activate 'just in case another worksheet is in focus
    wsopt.Range("12:12").Select
    ActiveWindow.FreezePanes = False
    ActiveWindow.FreezePanes = True
    
    'Shorten the name of the Order Type column to just Order.
    
    wsopt.Range("Q11").Value = "Order"
    
    'Rename the OT column to say Period and the data in it where M becomes Monthly spelled out, and O becomes Other spelled out.
    
    wsopt.Range("J11").Value = "Period"
    
    lastRow = wsopt.Range("A" & wsopt.Rows.Count).End(xlUp).Row
    Set r = wsopt.Range(wsopt.Range("J12"), wsopt.Cells(lastRow, "J"))
    
    'in case none found, turn on error trap
    On Error Resume Next
    r.Replace what:="M", replacement:="Monthly", lookAt:=xlWhole
    r.Replace what:="O", replacement:="Other", lookAt:=xlWhole
    On Error GoTo 0
    
    'Left justify the data in all columns except for P#, S#, L#, Qty, Strike, Days which should be centered.
    
    'first make all left justified
    Set r = wsopt.Range(wsopt.Range("A12"), wsopt.Cells(lastRow, "S"))
    With r
        .HorizontalAlignment = xlLeft
        .VerticalAlignment = xlBottom
    End With
    
    'now make particular columns centered
    Set r = Union(wsopt.Range("H12:H" & lastRow), wsopt.Range("L12:L" & lastRow), wsopt.Range("N12:N" & lastRow), wsopt.Range("P12:P" & lastRow), wsopt.Range("S12:S" & lastRow))
    With r
        .HorizontalAlignment = xlCenter
    End With
    
    'Header row should always remain left justified.
    '
    'Nothing to do?
    '
    
    'Add a Total Row at the bottom that simply displays a count for the number notes that are filled in for that column, and leaves every other total empty.
    For Each r In wsopt.Range("A" & lastRow + 2, wsopt.Range("S" & lastRow + 2))
        If r.Column = 1 Then
            r.Value = "TOTAL"
        ElseIf IsNumeric(wsopt.Cells(12, r.Column).Value) Then 'test the last row for numeric versus text values - if numeric, then provide count
            Dim cntAddr As String
            cntAddr = wsopt.Range(wsopt.Cells(12, r.Column), wsopt.Cells(lastRow, r.Column)).Address
            r.Value = Evaluate("COUNT(" & cntAddr & ")")
        End If
    Next r
    
    'Auto-fit all columns to width of data with the exception of the Notes column.
    wsopt.Range("B:S").EntireColumn.AutoFit
        
    'Always return focus to cell A1.
    wsopt.Range("A1").Select
    ActiveWindow.ScrollRow = 1
    ActiveWindow.ScrollColumn = 1

End Sub

Open in new window


Dave
0
rtod2Author Commented:
Please clarify.  I'm definitely scared to accept final output for which there are no notes about what it does or particularly next to something that was 'undone' or commented out.  That isn't good.  If you don't quite understand it then goflow needs to look at it first. Since this is a working copy, I need to make sure I am not missing something I need.
0
dlmilleCommented:
>>Currently the macro runs on all the tabs in the workbook and hopefully, that will still be the case when I am finished cleaning it up a little. If possible, please try not to re-post the workbook itself, but rather just the code as done below.

Is the statement above correct?  You provided a workbook and set of code that is currently inoperable as a result of running any of the macros.

Did you possibly post the incorrect code or workbook?  Have you tested what you had already?  Does it work and perhaps I'm missing something?  If that's the case, I stand corrected.

Please advise, as it will take me literally 5 x the time and effort to fully test what you had to start with, fixing what needs to be fixed, than it did to respond to the essence of this request.

If I'm correct, you closed out a perfectly good question which goflow answered yet was answered incomplete.  I'm not sure how to respond to that.

Technically, I can put a call to the cleanOutput routine anywhere at the END of the process of creating the output tab.  Should I be called on to make sure EVERYTHING ELSE works as part of this request?

Please advise,

Dave
0
dlmilleCommented:
To be fair, the other question you asked would have been the one to tie all this together.  The call to cleanOutput is the LAST statement following goflow's input.  If things didn't work as a result of that, THAT question would be the one to work it out on.

Have I lost it, or am I making any sense at all? (long day here :)

I'm not really frustrated and I'm sure you might be getting there, I'm just trying to draw the line here on scope, so we can both be efficient.

Cheers mate.

Dave
0
dlmilleCommented:
Perhaps if you told me what

TradeReport

is, that could be useful, as goflow's guidance was all about that which might be the rosetta stone for what we need to finish this up?  You might need to post a link to it.

Dave
0
rtod2Author Commented:
Dave,
Thank you for that. I just tested it and the previous code does run on all four tabs in this test1.2p version.  There is a problem with the way the notes are being pulled from the rm data type but the macro does run.  

If we could at least add the formatting to that without breaking, commenting out, or undoing any previous work, then it would be a big help. That is part of the problem with this EE format. Once a project gets complicated, other things like chat, screen sharing, and private messaging become necessary.

Thank you for any further assistance you can provide.
0
rtod2Author Commented:
Hmm.  TradeReport is the sub from where development started.  I can tell you what the macro is designed to do but that may not be what you are asking.

I have re-written the comments for the top of the code as follows:

'This macro first looks to see which tab is selected and identifies a data type of rm or pm based'
'solely on the way the data appears within it. It then copies the data from the Trade History'
'section of the original tab and creates a properly formatted Output tab with a table for the'
'that data, and then sorts each Spread into meaningful positions. It then tries to also copy the'
'notes from the original Order History section into the appropriate cell for each Spread. Just'
'like with creating the table, the notes rely heavily on determining whether the originating data'
'type is rm or pm.'
0
dlmilleCommented:
If you post TradeReport, all may be revealed.

Dave
0
rtod2Author Commented:
Here is the original version with the code in it.  This is what you said wasn't working.  I've tested it and it is.  The only what I need now is a fix for the formatting of the output tab without disabling anything already here test1.2p version
0
dlmilleCommented:
>> This is what you said wasn't working

Is thist correct?  I stated that the post to the workbook in your original question wasn't working ;)

PS - I just downloaded and tried to run a macro with now luck.

The work to clean your output is 100%.

So, please advise.  Precisely, HOW did you test this?

0
dlmilleCommented:
Never mind.  I get it.  You have a MACRO called TradeReport in the code.

I can deal.

Give me 5

Dave
0
dlmilleCommented:
Ok - that clarifies everything - knowing what the key macro is and where it is.  Sorry for all the confusion :)  And thanks for your patience in this as well.

Here's the revised code.  I just ran TradeReport and the last thing it does is cleanOutput.

Perhaps it might have helped if you'd told me what the main macro was that triggered everything?

I take a big hit on this one, I did a search for the command "set wsopt" and must have mistyped as I assumed the code was broken from that, lol.  Lesson learned - I can make a mistake, lol

Frankly, that was my original direction - run it as the last step.  At any rate, I think we're there.

Here's the code - all integrated.  I ran this and it did the work soup to nuts, including the steps you asked for in this thread.
 
Option Explicit
'--> This macro takes either pm or rm tabs and creates a properly formatted table in a new tab'
'called Output with the data from the Trade History section of the original tab. It also takes'
'the notes from the Order History section of the original tab and then indexes and sorts each'
'Spread into meaningful positions.'

'Future development will include hiding the Leg and Spread numbers, as well as making some
'calculations on each overall position.'

Const AOH = "Account Order History"
Const ATH = "Account Trade History"
Const PAL = "Profits and Losses"
Const EQT = "Equities"
Const OPT = "Options"
Const OTH = "Others"
Const FRX = "Forex"

Dim wsopt As Worksheet
    

Private Sub AddMOColumn()
'This Sub will Add A new Column before Exp Column J that should indicate either of the following
'M for Monthly when the date in Exp is formated as Mmm-yy the date should be the 3rd friday of the month
'O for Weekly or Quarterly options


Dim MaxRow As Long, I As Long
Dim dDate As Date
Dim ThirdThuOfTheMonth As Date
Dim a

MaxRow = wsopt.Rows(wsopt.Rows.Count).End(xlUp).Row
wsopt.Select
Columns("J:J").Select
Selection.Insert Shift:=xlToRight
wsopt.Range("J11") = "OT"

For I = 12 To MaxRow
    If wsopt.Cells(I, "K") <> "" Then
        If wsopt.Cells(I, "K").NumberFormat = "mmm-dd-yy" Then
            wsopt.Cells(I, "J") = "O"
        Else
            wsopt.Cells(I, "J") = "M"
            dDate = wsopt.Cells(I, "K")
            dDate = DateSerial(Year(dDate), Month(dDate), 1)
            Select Case Weekday(dDate)
                Case 5  'If Date is a Thursday then add 14 days
                    ThirdThuOfTheMonth = DateValue(dDate + 14)
                Case Is > 5 'If Date is Friday or saturday then add 21+1 days
                    ThirdThuOfTheMonth = DateValue(dDate + 21 - (Weekday(dDate) - vbThursday))
                Case Is < 5 'If Date is Sunday to Thurthday then add 14+ diffrence to friday days
                    ThirdThuOfTheMonth = DateValue(dDate + 14 + vbThursday - Weekday(dDate))
            End Select
            If Weekday(ThirdThuOfTheMonth) <> vbThursday Then
                MsgBox ("this date: " & ThirdThuOfTheMonth & " does not corespond to a Thursday! on row " & I & " Please check that date in Col K is actually a valid date then re-run the whole macro.")
            End If
            wsopt.Cells(I, "K") = ThirdThuOfTheMonth
        End If
    End If
Next I
End Sub

Private Sub AddDaysandPLColumn()
'This Sub will Add 3 new Columns
'Days to Exp in Col N next to type Column which should be the diffrence in days between Exec Time and Exp
'P/L Balance Col R
'P/L% Col S


Dim MaxRow As Long, I As Long
Dim dDate As Date
Dim ThirdThuOfTheMonth As Date
Dim a

MaxRow = wsopt.Rows(wsopt.Rows.Count).End(xlUp).Row
wsopt.Select
Columns("N:N").Select
Selection.Insert Shift:=xlToRight
wsopt.Range("N11") = "Days to Exp"
Columns("R:S").Select
Selection.Insert Shift:=xlToRight
wsopt.Range("R11") = "P/L Balance"
wsopt.Range("S11") = "P/L %"


For I = 12 To MaxRow
    If wsopt.Cells(I, "K") <> "" Then
        wsopt.Cells(I, "N") = DateValue(wsopt.Cells(I, "C")) - DateValue(wsopt.Cells(I, "K"))
    End If
    
    
Next I
End Sub


Sub TradeReport()
    Dim wsPM As Worksheet
    Dim aCell As Range, bCell As Range, cCell As Range, delRange As Range
    Dim AOHRow As Long, PALRow As Long, ATHRow As Long
    Dim lastRow As Long, I As Long, J As Long
    Dim shName As String
    Dim SearchString As String, MatchString As String, init1String As String, init2String As String
    Dim intNum  As Long
    Dim FirstAddress As String
    
    On Error GoTo Whoa
    
    Application.ScreenUpdating = True
    
    Set wsPM = ActiveSheet
    
    shName = wsPM.Name
        
    '--> Make New "Output" Sheet if one already exists'
    On Error Resume Next
    Application.DisplayAlerts = False
    Set wsopt = Sheets("Output")
    intNum = 0
    While Err.Number = 0
        Err.Clear
        intNum = intNum + 1
        Set wsopt = Sheets("Output" & intNum)
    Wend
    Err.Clear
    On Error GoTo 0
    Application.DisplayAlerts = True
    
    '--> Recreate "Output" Sheet and move it to the right'
    Set wsopt = Worksheets.Add(after:=Worksheets(Worksheets.Count))
    If intNum = 0 Then
        wsopt.Name = "Output"
    Else
        wsopt.Name = "Output" & intNum
    End If
    
    '--> Find the "Account Trade History" cell in Sheet PM'
    Set aCell = wsPM.Columns(1).Find(what:=ATH, LookIn:=xlFormulas, _
    lookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)
    
    '--> If "Account Trade History" is found'
    If Not aCell Is Nothing Then
        '--> Get the starting row of "Account Trade History"'
        ATHRow = aCell.Row
        
        If LCase(Left(shName, 2)) = "pm" Then
            '--> Find the "Options" cell in Sheet PM'
            Set bCell = wsPM.Columns(1).Find(what:=OPT, LookIn:=xlFormulas, _
            lookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False, SearchFormat:=False)
        
            If bCell Is Nothing Then
            '--> Find the "Forex" cell in Sheet PM if Options is not found'
                Set bCell = wsPM.Columns(1).Find(what:=FRX, LookIn:=xlFormulas, _
                lookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False)
            End If
            
            If bCell Is Nothing Then
            '--> Find the "Profits and Losses" cell in Sheet PM if Forex is not found'
                Set bCell = wsPM.Columns(1).Find(what:=PAL, LookIn:=xlFormulas, _
                lookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False)
            End If
        End If
        
        If LCase(Left(shName, 2)) = "rm" Then
            '--> Find the "Equities" cell in Sheet RM'
            Set bCell = wsPM.Columns(1).Find(what:=EQT, LookIn:=xlFormulas, _
            lookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False, SearchFormat:=False)
            
            If bCell Is Nothing Then
            '--> Find the "Others" cell in Sheet RM if Equities is not found
                Set bCell = wsPM.Columns(1).Find(what:=OTH, LookIn:=xlFormulas, _
                lookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False)
            End If
        End If
        
        '--> If "Profits and Losses" is found'
        If Not bCell Is Nothing Then
            '--> Get the starting row of "Profits and Losses"
            PALRow = bCell.Row
            
            '--> Output Trade History to new tab.'
            wsPM.Rows((ATHRow + 1) & ":" & (PALRow - 1)).Copy wsopt.Rows(1)
            
            If LCase(Left(shName, 2)) = "rm" Then
                wsopt.Select
                Columns("A:A").Select
                Selection.Insert Shift:=xlToRight
            End If
            
            With wsopt
                '--> Remove last three columns because they are duplicates.'
                .Columns("M:O").Delete Shift:=xlToLeft
                
                '--> Define the notes column.'
                .Range("A1").Value = "Notes"
                .Columns("A:A").Replace what:="DEFAULT", replacement:="", lookAt:=xlPart, _
                SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
                
                '--> Get the last row of Output Sheet'
                lastRow = .Cells.Find(what:="*", after:=[A1], SearchOrder:=xlByRows, _
                          SearchDirection:=xlPrevious).Row
                   
                '--> Unsure of what this section does?'
                Set cCell = wsPM.Columns(1).Find(what:=AOH, LookIn:=xlFormulas, _
                lookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                MatchCase:=False, SearchFormat:=False)
                
                If Not cCell Is Nothing Then
                    AOHRow = cCell.Row + 1
                    
                '--> Copy the notes into the new notes column.
                    wsPM.Range("IV:IV").ClearContents
                    For I = AOHRow To ATHRow
                            SearchString = wsPM.Range("D" & I).Value & "###" & _
                            wsPM.Range("F" & I).Value & "###" & _
                            wsPM.Range("G" & I).Value & "###" & _
                            wsPM.Range("H" & I).Value & "###" & _
                            wsPM.Range("I" & I).Value
                            wsPM.Range("IV" & I).Value = SearchString
                    Next I
                
                    For J = 2 To lastRow
                        MatchString = .Range("D" & J).Value & "###" & _
                                        .Range("F" & J).Value & "###" & _
                                        .Range("G" & J).Value & "###" & _
                                        .Range("H" & J).Value & "###" & _
                                        .Range("I" & J).Value
                
                            Set cCell = wsPM.Range("IV:IV").Find(what:=MatchString, LookIn:=xlFormulas, _
                                        lookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                                        MatchCase:=False, SearchFormat:=False)
                            If Not cCell Is Nothing Then
                                FirstAddress = cCell.Address
                                    Do
                                        If wsopt.Range("F" & J).Value = wsPM.Range("F" & cCell.Row).Value Then
                                            .Range("A" & J).Value = wsPM.Range("A" & cCell.Row).Value
                                            Exit Do
                                        Else
                                            Set cCell = wsPM.Range("IV:IV").FindNext(cCell)
                                        End If
                                    Loop While Not cCell Is Nothing And cCell.Address <> FirstAddress
                            End If
                    Next J
                End If
                GoTo There

                '--> Copy the notes into the new notes column. old'
                    For I = AOHRow To ATHRow
                        SearchString = wsPM.Range("D" & I).Value & "###" & _
                        wsPM.Range("F" & I).Value & "###" & _
                        wsPM.Range("G" & I).Value & "###" & _
                        wsPM.Range("H" & I).Value & "###" & _
                        wsPM.Range("I" & I).Value
                        init1String = wsPM.Range("F" & I).Value
                                       For J = 2 To lastRow
                            init2String = wsopt.Range("F" & J).Value
                
                           If init1String = init2String Then
                                MatchString = .Range("D" & J).Value & "###" & _
                                              .Range("F" & J).Value & "###" & _
                                              .Range("G" & J).Value & "###" & _
                                              .Range("H" & J).Value & "###" & _
                                              .Range("I" & J).Value
                
                               If MatchString = SearchString Then
                                   .Range("A" & J).Value = wsPM.Range("A" & I).Value
                               End If
                          End If
                        Next J
                    Next I
                'End If
                
There:
                '--> Make the Output tab into a table that can be filtered by the column headers.'
                .ListObjects.Add(xlSrcRange, Range("$A$1:$L$" & lastRow), , xlYes).Name = "Table1"
                .ListObjects("Table1").ShowTableStyleRowStripes = False
                'ListObjects("Table1").TableStyle = "TableStyleLight1"'
                .Columns("B:L").EntireColumn.AutoFit
                
            End With
        End If
    End If
    Application.ScreenUpdating = False
    NewUpdates
    FixDate
    Indexing
    Sorting
    AddMOColumn
    AddDaysandPLColumn
    If LCase(Left(shName, 2)) = "rm" Then
        UpdateNotes wsPM, AOHRow, ATHRow
    End If
    
    wsopt.Cells(1, 1).Select

    Call cleanOutput
    
    Application.ScreenUpdating = True

'--> Clean Up and Exit.'
LetsContinue:
    Application.ScreenUpdating = True
    Set aCell = Nothing: Set bCell = Nothing: Set cCell = Nothing: Set delRange = Nothing
    On Error Resume Next
    Set wsopt = Nothing: Set wsPM = Nothing
    On Error GoTo 0
    Exit Sub
    
'--> Error Handling'
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub
Sub cleanOutput()
Dim r As Range, rng As Range
Dim lastRow As Long

    'assumes output tab just generated and thus doesn't have total row already, etc., as it had been previously cleared...
    
    'Freeze panes on the first 11 rows so that the header row will always be visible when scrolling.

    ThisWorkbook.Activate 'just in case another workbook is on top

    wsopt.Activate 'just in case another worksheet is in focus
    wsopt.Range("12:12").Select
    ActiveWindow.FreezePanes = False
    ActiveWindow.FreezePanes = True
    
    'Shorten the name of the Order Type column to just Order.
    
    wsopt.Range("Q11").Value = "Order"
    
    'Rename the OT column to say Period and the data in it where M becomes Monthly spelled out, and O becomes Other spelled out.
    
    wsopt.Range("J11").Value = "Period"
    
    lastRow = wsopt.Range("A" & wsopt.Rows.Count).End(xlUp).Row
    Set r = wsopt.Range(wsopt.Range("J12"), wsopt.Cells(lastRow, "J"))
    
    'in case none found, turn on error trap
    On Error Resume Next
    r.Replace what:="M", replacement:="Monthly", lookAt:=xlWhole
    r.Replace what:="O", replacement:="Other", lookAt:=xlWhole
    On Error GoTo 0
    
    'Left justify the data in all columns except for P#, S#, L#, Qty, Strike, Days which should be centered.
    
    'first make all left justified
    Set r = wsopt.Range(wsopt.Range("A12"), wsopt.Cells(lastRow, "S"))
    With r
        .HorizontalAlignment = xlLeft
        .VerticalAlignment = xlBottom
    End With
    
    'now make particular columns centered
    Set r = Union(wsopt.Range("H12:H" & lastRow), wsopt.Range("L12:L" & lastRow), wsopt.Range("N12:N" & lastRow), wsopt.Range("P12:P" & lastRow), wsopt.Range("S12:S" & lastRow))
    With r
        .HorizontalAlignment = xlCenter
    End With
    
    'Header row should always remain left justified.
    '
    'Nothing to do?
    '
    
    'Add a Total Row at the bottom that simply displays a count for the number notes that are filled in for that column, and leaves every other total empty.
    For Each r In wsopt.Range("A" & lastRow + 2, wsopt.Range("S" & lastRow + 2))
        If r.Column = 1 Then
            r.Value = "TOTAL"
        ElseIf IsNumeric(wsopt.Cells(12, r.Column).Value) Then 'test the last row for numeric versus text values - if numeric, then provide count
            Dim cntAddr As String
            cntAddr = wsopt.Range(wsopt.Cells(12, r.Column), wsopt.Cells(lastRow, r.Column)).Address
            r.Value = Evaluate("COUNT(" & cntAddr & ")")
        End If
    Next r
    
    'Auto-fit all columns to width of data with the exception of the Notes column.
    wsopt.Range("B:S").EntireColumn.AutoFit
        
    'Always return focus to cell A1.
    wsopt.Range("A1").Select
    ActiveWindow.ScrollRow = 1
    ActiveWindow.ScrollColumn = 1

End Sub
Private Sub FixDate()
'This Sub will go thru Exp Column Col J and will Fix the date to allow for either mm-yy or mmm-dd-yy.

Dim MaxRow As Long, I As Long
Dim tmpM As String, tmpD As String, tmpY As String

MaxRow = wsopt.Rows(wsopt.Rows.Count).End(xlUp).Row

For I = 12 To MaxRow
    '---> Strip Dates and Fix them
    If wsopt.Cells(I, "J") <> "" Then
        If IsDate(wsopt.Cells(I, "J")) Then
            '---> Format normally if normal Date format as 'mmm-dd-yy'
            wsopt.Cells(I, "J").NumberFormat = "Mmm-yy"
        Else
            '---> Strip the date in Day month Year then re-group so system would recognize
            '     it as a date and then apply format 'mmm-yy'
            tmpM = Left(wsopt.Cells(I, "J"), 3)
            tmpY = Right(wsopt.Cells(I, "J"), 2)
            tmpD = Mid(wsopt.Cells(I, "J"), 4, Len(wsopt.Cells(I, "J")) - 6)
            wsopt.Cells(I, "J") = tmpM & " " & Format(Val(tmpD), "") & ", " & Format(Val(tmpY), "")
            wsopt.Cells(I, "J").NumberFormat = "Mmm-dd-yy"
        End If
    End If

Next I

End Sub

Private Sub NewUpdates()
Dim I As Integer

'---> Create extra space at the top of the table of approximately 10 rows.
wsopt.Rows("1:10").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove

'---> Modify the date format of the Exec Time column to reflect the format of ddd mmm dd, yyyy hh:mm'
'and the Exp column to reflect the format of mm-yy.'
For I = 12 To wsopt.Cells(wsopt.Rows.Count, "K").End(xlUp).Row
wsopt.Range("B" & I).NumberFormat = "ddd mmm-dd-yyyy hh:mm"
wsopt.Range("G" & I).NumberFormat = "mmm-yy"
Next I

'--> Add Columns for Postion, Spread, and Leg Numbers'
'Add P# column before the Exec Time column with the comment "Position #" in the header for the P# column.'
'Add  S# column between the Exec Time and Spread columns with the comment "Spread #" in the header for the S# column.'
'Add L# column between the Spread and Side columns with the comment "Leg #" in the header for the L# column.'
wsopt.Columns("B:B").Insert Shift:=xlToRight
wsopt.Columns("D:D").Insert Shift:=xlToRight
wsopt.Columns("F:F").Insert Shift:=xlToRight

'---> Format column D and E to number format
wsopt.Range("D12:D" & wsopt.Cells(wsopt.Rows.Count, "K").End(xlUp).Row).NumberFormat = "0"
wsopt.Range("F12:F" & wsopt.Cells(wsopt.Rows.Count, "K").End(xlUp).Row).NumberFormat = "0"
wsopt.Range("B12:B" & wsopt.Cells(wsopt.Rows.Count, "K").End(xlUp).Row).NumberFormat = "0"

'---> Rename the header of the added Position, Spread, and Leg Number columns'
wsopt.Range("B11") = "P#": wsopt.Range("D11") = "S#": wsopt.Range("F11") = "L#"

'---> Set autofit to the width of column D and E
wsopt.Columns("D:D").EntireColumn.AutoFit
wsopt.Columns("F:F").EntireColumn.AutoFit
wsopt.Columns("B:B").EntireColumn.AutoFit
'---> Add comments
wsopt.Range("B11").AddComment
wsopt.Range("B11").Comment.Visible = False
wsopt.Range("B11").Comment.Text Text:="Position No"
wsopt.Range("D11").AddComment
wsopt.Range("D11").Comment.Visible = False
wsopt.Range("D11").Comment.Text Text:="Spread No"
wsopt.Range("F11").AddComment
wsopt.Range("F11").Comment.Visible = False
wsopt.Range("F11").Comment.Text Text:="Leg No"

'---> Shrink the printout so all column will be printed in the same page
ActiveSheet.PageSetup.PrintArea = ""
wsopt.PageSetup.FitToPagesWide = 1
wsopt.PageSetup.FitToPagesTall = 1

End Sub

'DEFINITIONS - Definitions to understand prior to Indexing and Ordering'
'1. Positions - Positions can be made up of more than one Spread and the newest Positions appear at the top of the sheet.'
'2. Spreads - Spreads can be made up of more than one Leg and their order with a position can change.'
'3. Legs - Legs are made up of individual rows within a Spread and there order within the spread never changes.'

Private Sub Indexing()
'Each Position, Spread, and Leg is indexed with a number according to the value in its Exec Date column.'
'P# - Positions are numbered sequentially with 1 being  meaning that it contains a newer Exec Date than any other positions.'
'S# - Spreads are numbered sequentially with 1 meaning that it contains the a newer Exec Date than the other spreads.'
'L# - Legs are numbered sequentially with 1 containing the oldest Exec Date within it's particular spread and starting over at the next spread.'
'If the Exec Date column (which is actually a date and time stamp) contains the same values, then the Symbol is used in alphabetical order.'

Dim I As Integer, K As Double, Z As Double, J As Double, l As Double, test As Boolean, test1 As Boolean
Dim WS As Worksheet, q As Double, Rcount As Double, x As Double, SpreadNo As Double
Sheets.Add after:=Sheets(Sheets.Count)
Set WS = Sheets(Sheets.Count)
K = 0: Z = -1: Rcount = wsopt.Cells(wsopt.Rows.Count, "K").End(xlUp).Row: SpreadNo = 0

For I = 12 To Rcount

    If K = 0 And Z = -1 Then
        K = K + 1: Z = Z + 2:
        WS.Cells(K, Z) = wsopt.Range("I" & I) & wsopt.Range("J" & I) & wsopt.Range("L" & I) & " " & wsopt.Range("K" & I)
        
        For x = I + 1 To Rcount
        If wsopt.Range("C" & x) = "" Then
            If InStr(1, WS.Cells(K, Z), wsopt.Range("K" & x)) = 0 Then WS.Cells(K, Z) = WS.Cells(K, Z) & " " & wsopt.Range("K" & x)
        Else
        Exit For
        End If
        Next x
        WS.Cells(K + 1, Z) = wsopt.Range("C" & I) & wsopt.Range("E" & I)
        WS.Cells(K + 1, Z + 1) = WS.Cells(K, Z + 1) + 1
        wsopt.Range("B" & I) = 1:  wsopt.Range("F" & I) = 1
    Else
        If J = 0 Then J = 1
        If wsopt.Range("C" & I) = "" Then
            test = True
        Else
        test = False: q = -1
    For J = 1 To Z Step 2
        q = q + 1
        If InStr(1, WS.Cells(1, J), wsopt.Range("I" & I) & wsopt.Range("J" & I) & wsopt.Range("L" & I)) > 0 Then
        If InStr(1, WS.Cells(1, J), wsopt.Range("K" & I)) > 0 Then
            wsopt.Range("B" & I) = J - q: test = True
            For x = I + 1 To Rcount
            If wsopt.Range("C" & x) = "" Then
                If InStr(1, WS.Cells(K, J), wsopt.Range("K" & x)) = 0 Then WS.Cells(K, J) = WS.Cells(K, J) & " " & wsopt.Range("K" & x)
            Else
            Exit For
            End If
            Next x
        Else
            For x = I + 1 To Rcount
            If wsopt.Range("C" & x) = "" Then
                If InStr(1, WS.Cells(K, J), wsopt.Range("K" & x)) > 0 Then wsopt.Range("B" & I) = J - q: test = True
            Else
            Exit For
            End If
            Next x
            If test = True Then
            WS.Cells(K, J) = WS.Cells(K, J) & " " & wsopt.Range("K" & I)
            For x = I + 1 To Rcount
            If wsopt.Range("C" & x) = "" Then
                If InStr(1, WS.Cells(K, J), wsopt.Range("K" & x)) = 0 Then WS.Cells(K, J) = WS.Cells(K, Z) & " " & wsopt.Range("K" & x)
            Else
            Exit For
            End If
            Next x
            End If
        End If
        
        
        If test = True Then Exit For
        End If
        Next J
        End If
    
    If test = True Then
             l = WS.Cells(WS.Rows.Count, J).End(xlUp).Row + 1
        If wsopt.Range("C" & I) = "" Then
            If J = 0 Then wsopt.Range("B" & I) = 1 Else wsopt.Range("B" & I) = J - q
            WS.Cells(l - 1, J + 1) = WS.Cells(l - 1, J + 1) + 1
            wsopt.Range("F" & I) = WS.Cells(l - 1, J + 1)
        Else
            WS.Cells(l, J) = wsopt.Range("C" & I) & wsopt.Range("E" & I)
            WS.Cells(l, J + 1) = WS.Cells(l, J + 1) + 1
            wsopt.Range("F" & I) = 1
        End If
    Else
        K = 1: Z = Z + 2: q = q + 1
        WS.Cells(K, Z) = wsopt.Range("I" & I) & wsopt.Range("J" & I) & wsopt.Range("L" & I) & " " & wsopt.Range("K" & I)
        For x = I + 1 To Rcount
        If wsopt.Range("C" & x) = "" Then
            If InStr(1, WS.Cells(K, Z), wsopt.Range("K" & x)) = 0 Then WS.Cells(K, Z) = WS.Cells(K, Z) & " " & wsopt.Range("K" & x)
        Else
        Exit For
        End If
        Next x
        WS.Cells(K + 1, Z) = wsopt.Range("C" & I) & wsopt.Range("E" & I)
        WS.Cells(K + 1, Z + 1) = WS.Cells(K, Z + 1) + 1
        wsopt.Range("B" & I) = Z - q: wsopt.Range("F" & I) = 1
    End If
    End If
Next I
Application.DisplayAlerts = False
WS.Delete
Application.DisplayAlerts = True

'---> The empty cells in the Exec Time and Spread columns should take on the information'
'of the preceding cell because they are part of the same Spread.'

For I = 12 To Rcount
    If wsopt.Range("E" & I) = "" And I > 12 Then
    wsopt.Range("E" & I) = wsopt.Range("E" & I - 1)
    wsopt.Range("C" & I) = wsopt.Range("C" & I - 1)
    wsopt.Range("C" & I & ":E" & I).Font.Color = -5395027
    End If
Next I

wsopt.Sort.SortFields.Add Key:=Range("C11"), _
        SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
        
         With ActiveSheet.Sort
        .SetRange Range("A12:O" & Rcount)
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
For I = 12 To Rcount
     If wsopt.Range("F" & I) = 1 Then
        SpreadNo = SpreadNo + 1: wsopt.Range("D" & I) = SpreadNo
     Else
     wsopt.Range("D" & I) = SpreadNo
     End If
Next I
 
End Sub

Private Sub Sorting()

'Positions can contain single or multi-legged spreads but the sort order of the legs 'within' each'
'spread never changes. This is an important point because by contrast, the sort order in which each
'spread appears within the overall position does indeed change. Here the oldest spreads should'
'appear at the top of the position while newer spreads should appear at the bottom of the position.'

Dim I As Double, Brow As Double, Erow As Double, Prow As Double
Dim Rcount As Double

'On Error Resume Next
Rcount = wsopt.Cells(wsopt.Rows.Count, "B").End(xlUp).Row

 '---> Sorting the output by the Position No.
    wsopt.Sort.SortFields.Clear
    wsopt.Sort.SortFields.Add Key:=Range("B11"), _
        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
     
    With wsopt.Sort
        .SetRange Range("A11:O" & Rcount)
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    
'--> Skipping a row between each major position
For I = Rcount To 13 Step -1
If wsopt.Range("B" & I) <> wsopt.Range("B" & I - 1) And wsopt.Range("B" & I) <> "" Then
    wsopt.Rows(I & Chr(58) & I).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    
    '--> Added by gowflow to keep correct counting of last row
    Rcount = Rcount + 1
End If
Next I

'--> Sorting the output by Date descending
Brow = 0

'--> Changed by gowflow from upper Rcount to Rcount +1
wsopt.Sort.SortFields.Add Key:=wsopt.Range("C11"), _
    SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal

For I = 12 To Rcount
If wsopt.Range("B" & I) <> "" Then
    If Brow = 0 Then
        Brow = I: Erow = I
        Else
        Erow = I
    End If
Else
        
         With wsopt.Sort
        .SetRange Range("A" & Brow & ":O" & Erow)
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    Brow = 0
wsopt.Range("A" & I - 1 & ":O" & I - 1).Copy Destination:=wsopt.Range("A" & I & ":O" & I)
wsopt.Range("A" & I & ":O" & I).Font.ThemeColor = xlThemeColorDark1
End If
Next I

wsopt.Range("P" & 12) = wsopt.Range("D" & 12): Prow = wsopt.Range("D" & 12)
For I = 13 To Rcount
If wsopt.Range("B" & I) = wsopt.Range("B" & I - 1) Then
    wsopt.Range("P" & I) = Prow
Else
    Prow = wsopt.Range("D" & I)
    wsopt.Range("P" & I) = Prow
End If
Next I

wsopt.Range("B" & 12) = 1: Prow = 1
For I = 13 To Rcount
If wsopt.Range("P" & I) = wsopt.Range("P" & I - 1) Then
    wsopt.Range("B" & I) = Prow
    If wsopt.Range("P" & I) = wsopt.Range("P" & I + 1) Then wsopt.Range("B" & I).Font.Color = -5395027
Else
    Prow = Prow + 1
    wsopt.Range("B" & I) = Prow
End If
Next I
wsopt.Columns("P:P").Delete Shift:=xlToLeft
   
End Sub

Sub UpdateNotes(WS As Worksheet, FMRow As Long, TORow As Long)
'This Sub will update noted for rm sheets from the Account Order History section in Col A
'To match with data in the Output file created under wsopt variable.

Dim MaxRow As Long, I As Long, J As Long, K As Long, Z As Long
Dim Note As String
Dim NoteItem
Dim Row As Range
Dim Status
Dim ParClose As Long, RowMatched As Long, UnMatchedNotes As Long, NoteFound As Long
Dim BkRatio As Boolean, FoundIT As Boolean
Dim STMonth As Date, ENDMonth As Date


MaxRow = wsopt.Rows(wsopt.Rows.Count).End(xlUp).Row

'---> Clean the Area F to Z to dissec Notes
WS.Range("F" & FMRow & ":ZZ" & TORow).ClearContents
WS.Range("F" & FMRow & ":ZZ" & TORow).ClearFormats


'---> Clean the notes and copy to Col F only for Status Filled Notes
For I = FMRow + 1 To TORow
    Status = Split(WS.Cells(I, "D"), " ")
    For J = 0 To UBound(Status)
        If UCase(Status(J)) = "FILLED" Then
            '---> If a note start with (Replacing ... then remove the first part till the first space
            If Left(WS.Cells(I, "C"), 10) = "(Replacing" Then
                ParClose = InStr(1, WS.Cells(I, "C"), ")")
            Else
                ParClose = 0
            End If
            
            If ParClose <> 0 Then
                WS.Cells(I, "F") = Mid(WS.Cells(I, "C"), ParClose + 2, Len(WS.Cells(I, "C")) - ParClose - 1)
            Else
                WS.Cells(I, "F") = WS.Cells(I, "C")
            End If
            Note = WS.Cells(I, "F")
            NoteItem = Split(Note, " ")
            Z = 0
            
            '---> Check to see if BACKRATIO is found then treat the sequence diffrently
            If InStr(1, WS.Cells(I, "F"), "BACKRATIO") <> 0 Then
                BkRatio = True
            Else
                BkRatio = False
            End If
            
            '---> Loop thru all items in the Note
            For K = 0 To UBound(NoteItem)
                '---> Remove any items that has open/close brakets as this is comment
                If Left(NoteItem(K), 1) = "(" Or Right(NoteItem(K), 1) = ")" Then
                    K = K + 1
                    Z = Z - 1
                End If
                
                '---> Remove any first letter / at first position
                If Left(NoteItem(K), 1) = "/" Then NoteItem(K) = Right(NoteItem(K), Len(NoteItem(K)) - 1)
                
                '---> Keep only VERTICAL/BUTTERFLY/STRANGLE/DIAGONAL in Second position
                If K = 2 Then
                    If UCase(NoteItem(K)) = "VERTICAL" Or _
                       UCase(NoteItem(K)) = "BUTTERFLY" Or _
                       UCase(NoteItem(K)) = "STRANGLE" Or _
                       UCase(NoteItem(K)) = "DIAGONAL" Then
                        Z = 0
                    Else
                        Z = 1
                    End If
                End If
                
                If BkRatio Then
                    '---> If BACKRATIO encountered then treat the sequence diffrently.
                    Select Case K
                    Case 0
                        WS.Cells(I, K + 7).NumberFormat = "@"
                        WS.Cells(I, K + 7) = Format(NoteItem(0), "@")
                    Case 1, 2
                        WS.Cells(I, 7 + 1).NumberFormat = "@"
                        WS.Cells(I, 7 + 1) = Format(NoteItem(1) & " " & NoteItem(2), "@")
                    Case Else
                        WS.Cells(I, K + 7 - 1).NumberFormat = "@"
                        WS.Cells(I, K + 7 - 1) = Format(NoteItem(K), "@")
                    End Select
                Else
                    
                    If InStr(1, Note, "@") <> 0 Then
                        '---> in any sequence is @ is encountered make sure it is positioned
                        '     in Col P as it is the Price Column the rest will follow.
                        If Left(NoteItem(K), 1) = "@" And K + 7 + Z <> 16 Then
                            Z = 16 - 7 - K
                        End If
                    Else
                        If K + 7 + Z = 16 Then
                            Z = 16 - 7 - K + 1
                        End If
                    End If
                    WS.Cells(I, K + 7 + Z).NumberFormat = "@"
                    WS.Cells(I, K + 7 + Z) = Format(NoteItem(K), "@")
                End If
            Next K
        End If
    Next J
Next I


'---> Loop Again thru all the notes in the Account Order History section
'     and match the columns where there is data to find the threads in sheet output
'     Columns in Sheet   G H I J K L M N  O  P  Q
'     Columns in Output  G H E I - [K] L  M  P  Q
'     Column Num Output  7   5 9    11 12 13 16 17
'     Columns to check   Y   Y Y    Y  Y  Y  Y  Y

For I = FMRow + 1 To TORow
    
    If WS.Cells(I, "F") <> "" Then
        wsopt.UsedRange.AutoFilter 1, Criteria1:=""
        If WS.Cells(I, "G") <> "" Then wsopt.UsedRange.AutoFilter 7, WS.Cells(I, "G")
        If WS.Cells(I, "I") <> "" Then wsopt.UsedRange.AutoFilter 5, WS.Cells(I, "I")
        If WS.Cells(I, "J") <> "" Then wsopt.UsedRange.AutoFilter 9, WS.Cells(I, "J")
        If WS.Cells(I, "L") <> "" Then
            If Len(WS.Cells(I, "L")) = 3 Then
                On Error Resume Next
                STMonth = DateSerial(WS.Cells(I, "M"), Month(DateValue(WS.Cells(I, "L") & " 1," & Year(Now))), 1)
                ENDMonth = DateSerial(Year(STMonth), Month(STMonth), Day(Application.WorksheetFunction.EoMonth(STMonth, 0)))
                wsopt.UsedRange.AutoFilter 11, Criteria1:=">=" & STMonth, Operator:=xlAnd, Criteria2:="<=" & ENDMonth
            Else
                On Error Resume Next
                STMonth = DateValue(Left(WS.Cells(I, "L"), 3) & " " & Right(WS.Cells(I, "L"), Len(WS.Cells(I, "L")) - 3) & "," & WS.Cells(I, "M"))
                wsopt.UsedRange.AutoFilter 11, Criteria1:=">=" & STMonth, Operator:=xlAnd, Criteria2:="<=" & STMonth
            End If
        End If
        On Error GoTo 0
        If WS.Cells(I, "N") <> "" And InStr(1, WS.Cells(I, "N"), "/") = 0 Then wsopt.UsedRange.AutoFilter 12, WS.Cells(I, "N")
        If WS.Cells(I, "O") <> "" And InStr(1, WS.Cells(I, "N"), "/") = 0 Then wsopt.UsedRange.AutoFilter 13, WS.Cells(I, "O")
        'If WS.Cells(I, "P") <> "" Then wsopt.UsedRange.AutoFilter 16, Criteria1:="<=" & Val(Right(WS.Cells(I, "P"), Len(WS.Cells(I, "P")) - 1))
        If WS.Cells(I, "Q") <> "" Then wsopt.UsedRange.AutoFilter 17, WS.Cells(I, "Q")
        NoteFound = NoteFound + 1
        FoundIT = True
        
        For Each Row In wsopt.Range("11:" & MaxRow).EntireRow.SpecialCells(xlCellTypeVisible).Rows
            If wsopt.Cells(Row.Row, "A").EntireRow.Hidden = False And wsopt.Cells(Row.Row, "C") <> "" And Row.Row <> 11 Then
                wsopt.Cells(Row.Row, "A") = WS.Cells(I, "F")
                RowMatched = RowMatched + 1
                FoundIT = False
                Exit For
            End If
        Next Row
        
        If FoundIT Then
            'MsgBox (WS.Cells(I, "F") & Chr(10) & "Was not mached in sheet Output !")
            WS.Cells(I, "F").Interior.ColorIndex = 3
            UnMatchedNotes = UnMatchedNotes + 1
        End If
        
        '---> Clear All Filters
        wsopt.UsedRange.AutoFilter 1
        wsopt.UsedRange.AutoFilter 5
        wsopt.UsedRange.AutoFilter 7
        wsopt.UsedRange.AutoFilter 9
        wsopt.UsedRange.AutoFilter 11
        wsopt.UsedRange.AutoFilter 12
        wsopt.UsedRange.AutoFilter 13
        wsopt.UsedRange.AutoFilter 16
        wsopt.UsedRange.AutoFilter 17
    End If
Next I

MsgBox ("A total of " & RowMatched & " Spread items were matched with notes." & Chr(10) _
& "A total of " & NoteFound & " Notes FILLED were found in the Order History Section." & Chr(10) _
& "A total of " & UnMatchedNotes & " Notes were not Matched in Sheet Output.")

End Sub

Open in new window


And here's the subroutine you asked for that is ALREADY in the code posted just above, that gives you those steps you requested:
 
Sub cleanOutput()
Dim r As Range, rng As Range
Dim lastRow As Long

    'assumes output tab just generated and thus doesn't have total row already, etc., as it had been previously cleared...
    
    'Freeze panes on the first 11 rows so that the header row will always be visible when scrolling.

    ThisWorkbook.Activate 'just in case another workbook is on top

    wsopt.Activate 'just in case another worksheet is in focus
    wsopt.Range("12:12").Select
    ActiveWindow.FreezePanes = False
    ActiveWindow.FreezePanes = True
    
    'Shorten the name of the Order Type column to just Order.
    
    wsopt.Range("Q11").Value = "Order"
    
    'Rename the OT column to say Period and the data in it where M becomes Monthly spelled out, and O becomes Other spelled out.
    
    wsopt.Range("J11").Value = "Period"
    
    lastRow = wsopt.Range("A" & wsopt.Rows.Count).End(xlUp).Row
    Set r = wsopt.Range(wsopt.Range("J12"), wsopt.Cells(lastRow, "J"))
    
    'in case none found, turn on error trap
    On Error Resume Next
    r.Replace what:="M", replacement:="Monthly", lookAt:=xlWhole
    r.Replace what:="O", replacement:="Other", lookAt:=xlWhole
    On Error GoTo 0
    
    'Left justify the data in all columns except for P#, S#, L#, Qty, Strike, Days which should be centered.
    
    'first make all left justified
    Set r = wsopt.Range(wsopt.Range("A12"), wsopt.Cells(lastRow, "S"))
    With r
        .HorizontalAlignment = xlLeft
        .VerticalAlignment = xlBottom
    End With
    
    'now make particular columns centered
    Set r = Union(wsopt.Range("H12:H" & lastRow), wsopt.Range("L12:L" & lastRow), wsopt.Range("N12:N" & lastRow), wsopt.Range("P12:P" & lastRow), wsopt.Range("S12:S" & lastRow))
    With r
        .HorizontalAlignment = xlCenter
    End With
    
    'Header row should always remain left justified.
    '
    'Nothing to do?
    '
    
    'Add a Total Row at the bottom that simply displays a count for the number notes that are filled in for that column, and leaves every other total empty.
    For Each r In wsopt.Range("A" & lastRow + 2, wsopt.Range("S" & lastRow + 2))
        If r.Column = 1 Then
            r.Value = "TOTAL"
        ElseIf IsNumeric(wsopt.Cells(12, r.Column).Value) Then 'test the last row for numeric versus text values - if numeric, then provide count
            Dim cntAddr As String
            cntAddr = wsopt.Range(wsopt.Cells(12, r.Column), wsopt.Cells(lastRow, r.Column)).Address
            r.Value = Evaluate("COUNT(" & cntAddr & ")")
        End If
    Next r
    
    'Auto-fit all columns to width of data with the exception of the Notes column.
    wsopt.Range("B:S").EntireColumn.AutoFit
        
    'Always return focus to cell A1.
    wsopt.Range("A1").Select
    ActiveWindow.ScrollRow = 1
    ActiveWindow.ScrollColumn = 1

End Sub

Open in new window


Dave
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
dlmilleCommented:
Line 301 in the large code post shows exactly where I integrated the call to cleanOutput()

Cheers,

Dave
0
rtod2Author Commented:
Excellent!  Thank you sir.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Excel

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.