Consulting

Results 1 to 3 of 3

Thread: Looping thorugh all tasks fails after task deleted

  1. #1

    Looping thorugh all tasks fails after task deleted

    I am trying to loop through all tasks, check them against a condition and then delete the ones that match the condition. The problem I am having is that the foreach loop exists after I delete the first task. In the code below I am trying to identify whether the task matches one in a variant array (imported from excel)

    For Each Task In ActiveProject.Tasks
                
                If Task.Text10 = "Work Order" Then
                    FoundWO = False
                    For j = LBound(vData) To UBound(vData)
                        If vData(j, 2) = Task.Text3 Then 'Found the work order header, dont delete it
                            FoundWO = True
                            Exit For
                        End If
                    Next j
                    If FoundWO = False Then
                        Task.Delete
                    End If
                End If
            Next Task
    The loop will work fine UNTIL I delete the first task. After the delete it exits at the "Next Task" line.

    Can anyone help me understand why this is happening?

  2. #2
    Administrator
    VP-Knowledge Base
    VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    Try working backwards
    For j = UBound(vData) To LBound(vData) step -1
    MVP (Excel 2008-2010)

    Post a workbook with sample data and layout if you want a quicker solution.


    To help indent your macros try Smart Indent

    Please remember to mark threads 'Solved'

  3. #3
    Moderator VBAX Sage SamT's Avatar
    Joined
    Oct 2006
    Location
    Near Columbia
    Posts
    7,814
    Location
    I am trying to loop through all tasks, check them against a condition and then delete the ones that match the condition.
    For Each Task In ActiveProject.Tasks 
         
        If Task.Text10 = "Work Order" Then 
           For j = UBound(vData) to LBound(vData) Step -1
                If vData(j, 2) = Task.Text3 Then 'matches condition
                            Task.Delete 
                End If 
                'Alternate Condition:
                'vData(j, 2) <> Task.Text3
            Next j 
       End If 
    Next Task
    I expect the student to do their homework and find all the errrors I leeve in.


    Please take the time to read the Forum FAQ

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •