Attribute VB_Name = "AlreadyInstalled"
'==============================================================================
' Already Installed: MS Project macros for project managers
'   Chapter 2: 1 RAG Gantt, 2 Slipping or Critical, 3 Two-week lookahead,
'              4 Governance Review export (the RAID log to HTML)
'   Chapter 3: 5 Status Gantt with manual switches, 6 Hours Left task sheet,
'              7 RAID log, 8 Status Gantt bar styles
'
' Install: in MS Project press Alt+F11, then File > Import File and pick this .bas
' (or Insert > Module and paste). To use it in every project, import it into
' ProjectGlobal (Global.MPT). Run a macro with Alt+F8. Try it on a copy first.
'
' Field plan (change them to suit your schedule):
'   Text1  = RAG, calculated (macro 1)
'   RAID log (macros 4 and 7):
'   Text2  = Record Type: Risk / Issue / Assumption / Decision
'   Text3  = Owner
'   Text4  = Status: Open / Needs confirmation / Resolved / Closed
'   Text5  = Priority: High / Medium / Low / Informational
'   Text6  = Category, e.g. Resource constraint, Regulatory or compliance
'   Text7  = Release or phase
'   Text8  = RAID ID, e.g. RI-001
'   Text9  = Work item ID in your delivery tool
'   Date1  = Target resolution date
'   Date2  = Last review date
'   Task Notes = the full profile, under these headings, each on its own line:
'                BACKGROUND (PLAIN LANGUAGE), Overview, Current Situation,
'                Business Impact, ACTIONS, DECISIONS, OPEN QUESTIONS
'   Flag10 = Done, your manual switch (macro 5)
'   Text10 = PM Status, your manual switch: On track / At risk / Off track (macro 5)
'   Number10 = Scheduled Time Elapsed (%), calculated (macro 5)
'   Text11 = Status Label, calculated (macro 5)
'   Finish10 = Elapsed Through, calculated (macro 5)
'   Flag11-Flag14 = On track / At risk / Off track / Complete, for bar colors (macros 5 and 8)
'   Flag15 = Check: past finish and not Done (macro 5)
'   Text12 = Workstream: your epics or workstreams, as a drop-down (macro 5)
'   Number11 = Slip in working days against the baseline finish (macro 6)
'==============================================================================
Option Explicit

'------------------------------------------------------------------------------
' 1. RAG Gantt: a calculated Red/Amber/Green field plus a Gantt view that shows
'    baseline, late and critical bars next to the variance that drives the color.
'------------------------------------------------------------------------------
Sub CreateRAGGanttView()
    ' RAG rule: Red if finishing 10+ working days late vs. baseline, Amber if 5+.
    ' Finish Variance is stored in minutes; 480 minutes = one 8-hour day.
    CustomFieldRename FieldID:=pjCustomTaskText1, NewName:="RAG"
    CustomFieldSetFormula FieldID:=pjCustomTaskText1, Formula:= _
        "IIf([Baseline Finish]=ProjDateValue(""NA""),""No baseline""," & _
        "IIf([Finish Variance]/480>=10,""Red"",IIf([Finish Variance]/480>=5,""Amber"",""Green"")))"
    On Error Resume Next
    CustomFieldProperties FieldID:=pjCustomTaskText1, Attribute:=pjFieldAttributeFormula
    On Error GoTo 0

    BuildRAGTable
    ViewEditSingle Name:="RAG Gantt", Create:=True, Screen:=pjGantt, ShowInMenu:=True, _
        Table:="RAG Table", Filter:="All Tasks", Group:="No Group", HighlightFilter:=False
    ViewApply Name:="RAG Gantt"
    ShowHelpfulBars
End Sub

'------------------------------------------------------------------------------
' 2. Slipping or Critical: only the tasks that are late against baseline or on
'    the critical path. This is the view for an issues review.
'------------------------------------------------------------------------------
Sub CreateSlippingGanttView()
    BuildRAGTable
    FilterEdit Name:="Slipping or Critical", TaskFilter:=True, Create:=True, OverwriteExisting:=True, _
        FieldName:="Finish Variance", Test:="is greater than", Value:="0d", _
        ShowInMenu:=True, ShowSummaryTasks:=False
    FilterEdit Name:="Slipping or Critical", TaskFilter:=True, FieldName:="", _
        NewFieldName:="Critical", Test:="equals", Value:="Yes", Operation:="Or", ShowSummaryTasks:=False
    FilterEdit Name:="Slipping or Critical", TaskFilter:=True, FieldName:="", _
        NewFieldName:="% Complete", Test:="is less than", Value:="100%", Operation:="And", ShowSummaryTasks:=False
    ViewEditSingle Name:="Slipping Gantt", Create:=True, Screen:=pjGantt, ShowInMenu:=True, _
        Table:="RAG Table", Filter:="Slipping or Critical", Group:="No Group", HighlightFilter:=False
    ViewApply Name:="Slipping Gantt"
    ShowHelpfulBars
End Sub

'------------------------------------------------------------------------------
' 3. Two-week lookahead: unfinished work that is active or starts in the next
'    14 days. The view to walk through with the team every week.
'------------------------------------------------------------------------------
Sub CreateLookaheadGanttView()
    BuildRAGTable
    FilterEdit Name:="Next 14 Days", TaskFilter:=True, Create:=True, OverwriteExisting:=True, _
        FieldName:="Start", Test:="is less than or equal to", Value:=Format(Date + 14, "Short Date"), _
        ShowInMenu:=True, ShowSummaryTasks:=True
    FilterEdit Name:="Next 14 Days", TaskFilter:=True, FieldName:="", _
        NewFieldName:="Finish", Test:="is greater than or equal to", Value:=Format(Date, "Short Date"), _
        Operation:="And", ShowSummaryTasks:=True
    FilterEdit Name:="Next 14 Days", TaskFilter:=True, FieldName:="", _
        NewFieldName:="% Complete", Test:="is less than", Value:="100%", Operation:="And", ShowSummaryTasks:=True
    ViewEditSingle Name:="Lookahead Gantt", Create:=True, Screen:=pjGantt, ShowInMenu:=True, _
        Table:="RAG Table", Filter:="Next 14 Days", Group:="No Group", HighlightFilter:=False
    ViewApply Name:="Lookahead Gantt"
    ShowHelpfulBars
    On Error Resume Next
    EditGoTo Date:=Date          ' scroll the chart to today
    On Error GoTo 0
End Sub

'------------------------------------------------------------------------------
' 4. Governance Review export. Writes every active RAID log item (Status Open
'    or Needs confirmation) to one HTML page: a box per item with its details
'    and the full Notes, with the Notes headings turned into real headings.
'    The page is saved next to the project file, ready to email, print or
'    upload into an AI chat. The Glossary row (an ID ending in -000) is skipped.
'------------------------------------------------------------------------------
Sub ExportGovernanceReview()
    Dim t As Task, html As String, n As Long, path As String
    Dim regID As String, st As String

    If ActiveProject.Path = "" Then
        MsgBox "Please save the project first.", vbExclamation
        Exit Sub
    End If

    html = "<!DOCTYPE html><html><head><meta charset=""utf-8""><title>Governance Review</title><style>" & _
        "body{font-family:Calibri,Arial,sans-serif;margin:20px;max-width:960px}" & _
        "h1,h2{color:#4B2E83}h2{margin-top:0}" & _
        ".record{border:1px solid #d9d9d9;border-radius:4px;padding:12px;margin-bottom:14px}" & _
        ".meta{background:#f5f5f5;padding:8px;margin-bottom:10px}" & _
        ".notes{background:#fafafa;padding:10px}.notes h3{margin:12px 0 4px}.notes h4{margin:8px 0 2px}" & _
        "</style></head><body>" & _
        "<h1>RAID Log: " & Esc(ActiveProject.Name) & "</h1>" & _
        "<p><b>Generated:</b> " & Format(Now, "mm/dd/yyyy hh:mm AM/PM") & "</p>"

    For Each t In ActiveProject.Tasks
        If Not t Is Nothing Then
            regID = Trim(t.Text8)
            st = UCase(Trim(t.Text4))
            If Trim(t.Name) <> "" And regID <> "" And Right(regID, 4) <> "-000" _
               And (st = "OPEN" Or st = "NEEDS CONFIRMATION") Then
                n = n + 1
                html = html & "<div class=""record""><h2>" & Esc(regID) & " - " & Esc(t.Name) & "</h2>" & _
                    "<div class=""meta"">" & _
                    "<b>Type:</b> " & Esc(t.Text2) & "<br>" & _
                    "<b>Priority:</b> " & Esc(t.Text5) & "<br>" & _
                    "<b>Status:</b> " & Esc(t.Text4) & "<br>" & _
                    "<b>Owner:</b> " & Esc(t.Text3) & "<br>" & _
                    "<b>Category:</b> " & Esc(t.Text6) & "<br>" & _
                    "<b>Release Phase:</b> " & Esc(t.Text7) & "<br>" & _
                    "<b>Target date:</b> " & FmtDate(t.Date1) & " &middot; <b>Last reviewed:</b> " & FmtDate(t.Date2) & _
                    "</div><div class=""notes"">" & GovNotesToHtml(t.Notes) & "</div></div>"
            End If
        End If
    Next t
    html = html & "<hr><p><b>Total active governance items:</b> " & n & "</p></body></html>"

    path = ActiveProject.Path & "\Governance_Review_" & Format(Now, "yyyy-mm-dd_hhnnss") & ".html"
    Dim s As Object
    Set s = CreateObject("ADODB.Stream")       ' writes UTF-8 so accents and symbols survive
    s.Type = 2: s.Charset = "utf-8": s.Open
    s.WriteText html
    s.SaveToFile path, 2
    s.Close

    If MsgBox(n & " active governance items exported to:" & vbCrLf & path & vbCrLf & vbCrLf & _
              "Open it in your browser now?", vbInformation + vbYesNo, "Governance Review created") = vbYes Then
        CreateObject("Shell.Application").ShellExecute path
    End If
End Sub

'------------------------------------------------------------------------------
' 5. Status Gantt with manual switches. You flip two switches per task: Done
'    (Flag10) and PM Status (Text10: On track / At risk / Off track). Project
'    works out a scheduled time elapsed from the Status Date, capped at 99% until
'    you mark the task Done, and a Status label that drives the bar colors.
'    Two views: "Status Gantt - PM" for edits, "Status Gantt - Report" for the deck.
'------------------------------------------------------------------------------
Sub CreateStatusGanttViews()
    If CStr(ActiveProject.StatusDate) = "NA" Then ActiveProject.StatusDate = Date

    CustomFieldRename FieldID:=pjCustomTaskFlag10, NewName:="Done"

    CustomFieldRename FieldID:=pjCustomTaskText10, NewName:="PM Status"
    On Error Resume Next
    CustomFieldValueListAdd FieldID:=pjCustomTaskText10, Value:="On track"
    CustomFieldValueListAdd FieldID:=pjCustomTaskText10, Value:="At risk"
    CustomFieldValueListAdd FieldID:=pjCustomTaskText10, Value:="Off track"
    CustomFieldProperties FieldID:=pjCustomTaskText10, Attribute:=pjFieldAttributeValueList
    On Error GoTo 0

    SetFormula pjCustomTaskNumber10, "Scheduled Time Elapsed (%)", _
        "IIf([Flag10],100,IIf([Milestone],0,IIf([Status Date]<=[Start],0," & _
        "IIf([Status Date]>=[Finish],99,Int(ProjDateDiff([Start],[Status Date])/[Duration]*100)))))"
    SetFormula pjCustomTaskText11, "Status Label", _
        "IIf([Flag10],""Complete"",IIf([Text10]<>"""",[Text10]," & _
        "IIf([Status Date]<=[Start],""Not started"",""Not set"")))"
    SetFormula pjCustomTaskFinish10, "Elapsed Through", _
        "IIf([Flag10],[Finish],IIf([Status Date]<=[Start],[Start]," & _
        "IIf([Status Date]>=[Finish],[Finish],[Status Date])))"
    SetFormula pjCustomTaskFlag11, "Is On track", "[Text11]=""On track"""
    SetFormula pjCustomTaskFlag12, "Is At risk", "[Text11]=""At risk"""
    SetFormula pjCustomTaskFlag13, "Is Off track", "[Text11]=""Off track"""
    SetFormula pjCustomTaskFlag14, "Is Complete", "[Text11]=""Complete"""
    SetFormula pjCustomTaskFlag15, "Check", "Not [Flag10] And [Status Date]>[Finish]"

    CustomFieldRename FieldID:=pjCustomTaskText12, NewName:="Workstream"

    NewTable "Status PM Inputs"
    AddCol "Status PM Inputs", "Text12", 18, 0, "Workstream"
    AddCol "Status PM Inputs", "Name", 40, 0
    AddCol "Status PM Inputs", "Start", 11, 2
    AddCol "Status PM Inputs", "Finish", 11, 2
    AddCol "Status PM Inputs", "Flag10", 7, 1, "Done"
    AddCol "Status PM Inputs", "Text10", 11, 1, "PM Status"
    AddCol "Status PM Inputs", "Number10", 16, 2, "Time Elapsed (%)"
    AddCol "Status PM Inputs", "Text11", 11, 1, "Status"
    AddCol "Status PM Inputs", "Flag15", 7, 1, "Check"

    NewTable "Status Report"
    AddCol "Status Report", "Text12", 18, 0, "Workstream"
    AddCol "Status Report", "Name", 40, 0
    AddCol "Status Report", "Start", 11, 2
    AddCol "Status Report", "Finish", 11, 2
    AddCol "Status Report", "Number10", 16, 2, "Time Elapsed (%)"
    AddCol "Status Report", "Text11", 11, 1, "Status"

    ViewEditSingle Name:="Status Gantt - Report", Create:=True, Screen:=pjGantt, ShowInMenu:=True, _
        Table:="Status Report", Filter:="All Tasks", Group:="No Group", HighlightFilter:=False
    ViewEditSingle Name:="Status Gantt - PM", Create:=True, Screen:=pjGantt, ShowInMenu:=True, _
        Table:="Status PM Inputs", Filter:="All Tasks", Group:="No Group", HighlightFilter:=False
    ViewApply Name:="Status Gantt - PM"
    MsgBox "Views created. Now run SetStatusGanttBarStyles for the bar colors, add your " & _
        "workstream names to the Workstream drop-down, and set the graphical indicators, " & _
        "as described in Chapter 3.", vbInformation, "Status Gantt"
End Sub

'------------------------------------------------------------------------------
' 6. Hours Left task sheet. Each week you type the hours left into Remaining
'    Work; Project recalculates Work and % Work Complete and moves the Finish.
'    Target finish (the baseline) sits next to the forecast and actual finish,
'    and Slip shows how many working days the task has moved.
'------------------------------------------------------------------------------
Sub CreateHoursLeftSheet()
    ' Finish Variance is in minutes of working time; divide by the minutes in a working day.
    SetFormula pjCustomTaskNumber11, "Slip (workdays)", _
        "IIf([Baseline Finish]=ProjDateValue(""NA""),0,[Finish Variance]/[Minutes Per Day])"

    NewTable "Hours Left"
    AddCol "Hours Left", "Name", 36, 0
    AddCol "Hours Left", "Resource Names", 16, 0
    AddCol "Hours Left", "Work", 8, 2
    AddCol "Hours Left", "Actual Work", 9, 2, "Actual"
    AddCol "Hours Left", "Remaining Work", 10, 2, "Hours left"
    AddCol "Hours Left", "% Work Complete", 9, 2, "% Complete"
    AddCol "Hours Left", "Baseline Finish", 11, 2, "Target finish"
    AddCol "Hours Left", "Finish", 11, 2, "Forecast finish"
    AddCol "Hours Left", "Actual Finish", 11, 2
    AddCol "Hours Left", "Number11", 9, 2, "Slip (days)"

    FilterEdit Name:="Unfinished Tasks Only", TaskFilter:=True, Create:=True, OverwriteExisting:=True, _
        FieldName:="% Complete", Test:="is less than", Value:="100%", ShowInMenu:=True, ShowSummaryTasks:=False
    FilterEdit Name:="Unfinished Tasks Only", TaskFilter:=True, FieldName:="", _
        NewFieldName:="Summary", Test:="equals", Value:="No", Operation:="And", ShowSummaryTasks:=False

    ViewEditSingle Name:="Hours Left", Create:=True, Screen:=pjTaskSheet, ShowInMenu:=True, _
        Table:="Hours Left", Filter:="Unfinished Tasks Only", Group:="No Group", HighlightFilter:=False
    ViewApply Name:="Hours Left"
End Sub

'------------------------------------------------------------------------------
' 7. RAID log as a split view: the RAID log table on top, the
'    Task Form underneath so you read and edit the full Notes for the row you
'    click. Each item is a task with no links and no work. Keep the RAID log in
'    its own Project file, or under a "Risks and issues" summary in the schedule
'    (then apply the "RAID Items" filter). Macro 4 exports it to HTML.
'------------------------------------------------------------------------------
Sub CreateRAIDLog()
    PickList pjCustomTaskText2, "Record Type", Array("Risk", "Issue", "Assumption", "Decision")
    CustomFieldRename FieldID:=pjCustomTaskText3, NewName:="Owner"
    PickList pjCustomTaskText4, "RI Status", Array("Open", "Needs confirmation", "Resolved", "Closed")
    PickList pjCustomTaskText5, "RI Priority", Array("High", "Medium", "Low", "Informational")
    PickList pjCustomTaskText6, "Category", Array("Business dependency or approval", _
        "External technical dependency", "Resource constraint", "Regulatory or compliance", _
        "Release readiness", "Other")
    CustomFieldRename FieldID:=pjCustomTaskText7, NewName:="Release or Phase"
    CustomFieldRename FieldID:=pjCustomTaskText8, NewName:="RAID ID"
    CustomFieldRename FieldID:=pjCustomTaskText9, NewName:="Work Item ID"
    CustomFieldRename FieldID:=pjCustomTaskDate1, NewName:="Target Resolution Date"
    CustomFieldRename FieldID:=pjCustomTaskDate2, NewName:="Last Review Date"

    NewTable "RAID"
    AddCol "RAID", "Text8", 9, 0, "ID"
    AddCol "RAID", "Name", 34, 0, "Title"
    AddCol "RAID", "Text2", 9, 1, "Type"
    AddCol "RAID", "Text5", 8, 1, "Priority"
    AddCol "RAID", "Text4", 12, 1, "Status"
    AddCol "RAID", "Text3", 14, 0, "Owner"
    AddCol "RAID", "Text6", 16, 0, "Category"
    AddCol "RAID", "Text7", 10, 0, "Release"
    AddCol "RAID", "Text9", 10, 0, "Work item"
    AddCol "RAID", "Date1", 11, 2, "Target date"
    AddCol "RAID", "Date2", 11, 2, "Last reviewed"

    FilterEdit Name:="RAID Items", TaskFilter:=True, Create:=True, OverwriteExisting:=True, _
        FieldName:="Text2", Test:="does not equal", Value:="", ShowInMenu:=True, ShowSummaryTasks:=False
    FilterEdit Name:="Active RAID Items", TaskFilter:=True, Create:=True, OverwriteExisting:=True, _
        FieldName:="Text4", Test:="equals", Value:="Open", ShowInMenu:=True, ShowSummaryTasks:=False
    FilterEdit Name:="Active RAID Items", TaskFilter:=True, FieldName:="", _
        NewFieldName:="Text4", Test:="equals", Value:="Needs confirmation", Operation:="Or", ShowSummaryTasks:=False

    ViewEditSingle Name:="RAID Sheet", Create:=True, Screen:=pjTaskSheet, ShowInMenu:=False, _
        Table:="RAID", Filter:="All Tasks", Group:="No Group", HighlightFilter:=False
    ViewEditCombination Name:="RAID Log", Create:=True, TopView:="RAID Sheet", _
        BottomView:="Task Form", ShowInMenu:=True
    ViewApply Name:="RAID Log"
    MsgBox "RAID Log view created. Click in the bottom pane and choose Format > Details > Notes " & _
        "so it shows the full profile of the row you select.", vbInformation, "RAID log"
End Sub

'------------------------------------------------------------------------------
' 8. Status Gantt bar styles: sets the bar colors in both Status Gantt views, so
'    you don't type them in Format > Bar Styles. Run macro 5 first. Safe to run
'    again: it replaces its own "Status ..." styles and leaves the others alone.
'    Needs Project 2010 or later (GanttBarEditEx and GridlinesEditEx). If a
'    step fails, it says which one, and you set the colors by hand as
'    described in Chapter 3.
'------------------------------------------------------------------------------
Sub SetStatusGanttBarStyles()
    Dim labels As Variant, flags As Variant, light As Variant, solid As Variant
    Dim v As Variant, i As Integer, stage As String
    Const NOT_SET As String = "Normal,Not Flag11,Not Flag12,Not Flag13,Not Flag14"

    labels = Array("On track", "At risk", "Off track", "Complete")
    flags = Array("Flag11", "Flag12", "Flag13", "Flag14")
    light = Array(RGB(&HD9, &HEE, &HDF), RGB(&HF8, &HEB, &HC7), RGB(&HF6, &HD8, &HD5), RGB(&HDF, &HE3, &HE7))
    solid = Array(RGB(&H1E, &H8A, &H3C), RGB(&HD4, &H92, &H0), RGB(&HC8, &H37, &H2F), RGB(&H46, &H52, &H5E))

    On Error GoTo Failed
    For Each v In Array("Status Gantt - PM", "Status Gantt - Report")
        stage = "opening the view """ & v & """. Run CreateStatusGanttViews first"
        ViewApply Name:=CStr(v)
        RemoveStatusBars

        ' Light bars for the whole task, then solid bars for the elapsed part.
        ' Styles lower in the list draw on top, so the order matters.
        stage = "adding the bar styles in """ & v & """ (GanttBarEditEx)"
        For i = 0 To 3
            AddStatusBar "Status Remaining - " & labels(i), "Normal," & flags(i), "Finish", light(i), False
        Next i
        AddStatusBar "Status Remaining - Not set", NOT_SET, "Finish", RGB(&HEE, &HF0, &HF2), False
        For i = 0 To 3
            AddStatusBar "Status Elapsed - " & labels(i), "Normal," & flags(i), "Finish10", solid(i), True
        Next i
        AddStatusBar "Status Elapsed - Not set", NOT_SET, "Finish10", RGB(&H9A, &HA4, &HAD), True

        ' Optional extras: skipped quietly if your version doesn't support them.
        On Error Resume Next
        GanttBarStyleBaseline Baseline:=pjBaseline, Show:=True
        GridlinesEditEx Item:=pjGanttStatusDate, NormalType:=pjContinuous, NormalColor:=RGB(&HB8, &H18, &H5A)
        On Error GoTo Failed
    Next v

    ViewApply Name:="Status Gantt - PM"
    MsgBox "Bar styles set in both Status Gantt views. Check them in Format > Bar Styles: " & _
        "you should see ten rows that start with ""Status"".", vbInformation, "Status Gantt bar styles"
    Exit Sub

Failed:
    MsgBox "The bar styles stopped while " & stage & "." & vbCrLf & _
        "Error " & Err.Number & ": " & Err.Description & vbCrLf & vbCrLf & _
        "Running this macro again replaces any styles it already added. If the error " & _
        "comes back, set the bar colors by hand in Format > Bar Styles, as described in Chapter 3.", _
        vbExclamation, "Status Gantt bar styles"
End Sub

'==============================================================================
' Helpers
'==============================================================================
Private Sub BuildRAGTable()
    TableEditEx Name:="RAG Table", TaskTable:=True, Create:=True, OverwriteExisting:=True, _
        FieldName:="ID", Title:="", Width:=6, Align:=1, ShowInMenu:=True, LockFirstColumn:=True, _
        DateFormat:=255, RowHeight:=1, ColumnPosition:=0, AlignTitle:=1
    AddCol "RAG Table", "Text1", 8, 1, "RAG"
    AddCol "RAG Table", "Name", 40, 0
    AddCol "RAG Table", "Resource Names", 16, 0
    AddCol "RAG Table", "Start", 11, 2
    AddCol "RAG Table", "Finish", 11, 2
    AddCol "RAG Table", "Baseline Finish", 11, 2
    AddCol "RAG Table", "Finish Variance", 9, 2
    AddCol "RAG Table", "Remaining Work", 10, 2
End Sub

Private Sub NewTable(tableName As String)
    ' Creates (or resets) a task table that starts with the ID column.
    TableEditEx Name:=tableName, TaskTable:=True, Create:=True, OverwriteExisting:=True, _
        FieldName:="ID", Title:="", Width:=6, Align:=1, ShowInMenu:=True, LockFirstColumn:=True, _
        DateFormat:=255, RowHeight:=1, ColumnPosition:=0, AlignTitle:=1
End Sub

Private Sub PickList(fieldID As Long, fieldName As String, values As Variant)
    ' Renames a text field and gives it a drop-down list of values.
    Dim v As Variant
    CustomFieldRename FieldID:=fieldID, NewName:=fieldName
    On Error Resume Next
    For Each v In values
        CustomFieldValueListAdd FieldID:=fieldID, Value:=CStr(v)
    Next v
    CustomFieldProperties FieldID:=fieldID, Attribute:=pjFieldAttributeValueList
    On Error GoTo 0
End Sub

Private Sub SetFormula(fieldID As Long, fieldName As String, formula As String)
    CustomFieldRename FieldID:=fieldID, NewName:=fieldName
    CustomFieldSetFormula FieldID:=fieldID, Formula:=formula
    On Error Resume Next
    CustomFieldProperties FieldID:=fieldID, Attribute:=pjFieldAttributeFormula
    On Error GoTo 0
End Sub

Private Sub AddCol(tableName As String, fieldName As String, colWidth As Integer, _
                   colAlign As Integer, Optional colTitle As String = "")
    TableEditEx Name:=tableName, TaskTable:=True, NewFieldName:=fieldName, Title:=colTitle, _
        Width:=colWidth, Align:=colAlign, LockFirstColumn:=True, DateFormat:=255, RowHeight:=1, AlignTitle:=1
End Sub

Private Sub ShowHelpfulBars()
    ' Available in Project 2010 and later; ignored quietly on older versions.
    On Error Resume Next
    GanttBarStyleCritical Show:=True
    GanttBarStyleLate Show:=True
    GanttBarStyleBaseline Baseline:=pjBaseline, Show:=True
    On Error GoTo 0
End Sub

Private Sub AddStatusBar(ByVal styleName As String, ByVal showFor As String, ByVal toField As String, _
                         ByVal barColor As Long, ByVal showPercent As Boolean)
    ' Adds one bar style at the end of the list, from Start to toField, in an RGB color.
    ' Arguments are by position (Item, Create, Name, StartShape, StartType, StartColor,
    ' MiddleShape, MiddleColor, MiddlePattern, EndShape, EndType, EndColor, ShowFor, Row,
    ' From, To, BottomText, TopText, LeftText, RightText) because To is a VBA keyword.
    ' MiddlePattern 1 = solid fill.
    If showPercent Then
        GanttBarEditEx "-1", True, styleName, pjNone, , , pjRectangleBar, barColor, 1, pjNone, , , _
            showFor, 1, "Start", toField, , , , "Number10"
    Else
        GanttBarEditEx "-1", True, styleName, pjNone, , , pjRectangleBar, barColor, 1, pjNone, , , _
            showFor, 1, "Start", toField
    End If
End Sub

Private Sub RemoveStatusBars()
    ' Deletes the styles this module added before, so running it twice doesn't double them.
    Dim s As Variant, kind As Variant, n As Integer, ok As Boolean
    On Error Resume Next
    For Each kind In Array("Status Remaining - ", "Status Elapsed - ")
        For Each s In Array("On track", "At risk", "Off track", "Complete", "Not set")
            For n = 1 To 3
                Err.Clear
                ok = False
                ok = GanttBarStyleDelete(Item:=kind & s)
                If Err.Number <> 0 Or Not ok Then Exit For
            Next n
        Next s
    Next kind
    On Error GoTo 0
End Sub

Private Function Esc(ByVal x As String) As String
    x = Replace(x, "&", "&amp;")
    x = Replace(x, "<", "&lt;")
    x = Replace(x, ">", "&gt;")
    Esc = x
End Function

Private Function FmtDate(ByVal d As Variant) As String
    If IsDate(d) Then FmtDate = Format(d, "yyyy-mm-dd") Else FmtDate = ""
End Function

Private Function GovNotesToHtml(ByVal x As String) As String
    ' Turns the Notes into HTML. A line that is exactly one of the section
    ' headings becomes a heading; every other line is kept as text.
    Dim lines() As String, i As Long, ln As String, out As String
    If Len(Trim(x)) = 0 Then GovNotesToHtml = "<em>No notes yet.</em>": Exit Function
    x = Replace(Replace(x, vbCrLf, vbLf), vbCr, vbLf)
    lines = Split(x, vbLf)
    For i = LBound(lines) To UBound(lines)
        ln = Trim(lines(i))
        Select Case UCase(ln)
            Case "BACKGROUND (PLAIN LANGUAGE)", "ACTIONS", "DECISIONS", "OPEN QUESTIONS"
                out = out & "<h3>" & Esc(ln) & "</h3>"
            Case "OVERVIEW", "CURRENT SITUATION", "BUSINESS IMPACT"
                out = out & "<h4>" & Esc(ln) & "</h4>"
            Case Else
                out = out & Esc(lines(i)) & "<br>"
        End Select
    Next i
    GovNotesToHtml = out
End Function
