Search code examples
vbams-project

Color coding summary tasks in using VBA in MS Project


we use a stage-gate framework and would like to color code each of the stages based on our colors. I've got the following code working, however, it continues to loop through about 30 times.

It doesn't need to keep looping though but not sure how to handle it. Any help to make this better would be appreciated.

Each Stage is at the first Summary level

Sub FindFieldByPriority2()
Dim ProjTasks   As Tasks
Dim ProjTask    As Task

Set ProjTasks = ActiveProject.Tasks
        If ProjTask.Summary = True Then
            
            Find Field:="Name", Test:="contains", Value:="STAGE 1 -"
            SelectRow
            Font32Ex Color:=16777215, CellColor:=50417
            
            Find Field:="Name", Test:="contains", Value:="STAGE 2 -"
            SelectRow
            Font32Ex Color:=16777215, CellColor:=1597656
            
            Find Field:="Name", Test:="contains", Value:="STAGE 3 -"
            SelectRow
            Font32Ex Color:=16777215, CellColor:=4925715
            
            Find Field:="Name", Test:="contains", Value:="STAGE 4 -"
            SelectRow
            Font32Ex Color:=16777215, CellColor:=4898666
    End If

Next ProjTask

End Sub


Solution

  • This code loops through the tasks and formats level 1 summary tasks based on the task name.

    Sub FormatLevel1SummaryTasks()
    
        FilterApply "All Tasks"
        SelectAll
        OutlineShowAllTasks
        
        Dim tsk As Task
        For Each tsk In ActiveProject.Tasks
            If Not tsk Is Nothing Then
                If tsk.OutlineLevel = 1 Then
                    
                    Find Field:="Unique ID", Test:="equals", Value:=tsk.UniqueID
                    If ActiveCell.Task.UniqueID = tsk.UniqueID Then
            
                        Select Case Left$(tsk.Name, 10)
                            Case Is = "STAGE 1 - "
                                Font32Ex Color:=16777215, CellColor:=50417
                            Case Is = "STAGE 2 - "
                                Font32Ex Color:=16777215, CellColor:=1597656
                            Case Is = "STAGE 3 - "
                                Font32Ex Color:=16777215, CellColor:=4925715
                            Case Is = "STAGE 4 - "
                                Font32Ex Color:=16777215, CellColor:=4898666
                            Case Else
                        End Select
        
                    End If
                End If
            End If
        Next tsk
        
    End Sub
    

    Note: to only format visible tasks, remove the first three lines of code.