Try this:
Option Explicit
Sub FINALIZE_SOURCE_DATA_BY_PART_TMS()
Dim lEndRow As Long, lEndColumn As Long, sEndColumn As String
Application.ScreenUpdating = False
With Sheets("CombinedPivot")
lEndRow = .Cells(Rows.Count, 1).End(xlUp).Row
lEndColumn = .Range("A1").End(xlToRight).Column
' check if macro has been run before
If .Cells(1, lEndColumn).Value = "Source Code 2" Then
' and adjust the last column number if it has
lEndColumn = lEndColumn - 4
End If
' determine the last column letter(s)
sEndColumn = Split(Cells(lEndRow, lEndColumn).Address, "$")(1)
With .Cells(1, lEndColumn)
' drop the headings into row 1
.Offset(0, 1).Value = "Count of Source Code 1"
.Offset(0, 2).Value = "Source Code 1"
.Offset(0, 3).Value = "Count of Source Code 2"
.Offset(0, 4).Value = "Source Code 2"
' drop the formulae into *ALL* the rows
.Offset(1, 1).Resize(lEndRow - 1).Formula = "=IFERROR(LARGE(B2:" & sEndColumn & "2,1),""N/A"")"
.Offset(1, 3).Resize(lEndRow - 1).Formula = "=IFERROR(LARGE(B2:" & sEndColumn & "2,2),""N/A"")"
.Offset(1, 2).Resize(lEndRow - 1).Formula2 = "=XLOOKUP(JB2,B2:" & sEndColumn & "2,$B$1:" & sEndColumn & "$1,""N/A"")"
.Offset(1, 4).Resize(lEndRow - 1).Formula2 = "=XLOOKUP(JD2,B2:" & sEndColumn & "2,$B$1:" & sEndColumn & "$1,""N/A"")"
End With
End With
Application.ScreenUpdating = True
End Sub
Bookmarks