+ Reply to Thread
Results 1 to 6 of 6

Do while loop very slow?

Hybrid View

  1. #1
    Registered User
    Join Date
    05-08-2017
    Location
    Paris
    MS-Off Ver
    2013
    Posts
    35

    Do while loop very slow?

    Dear all,

    In my excel file I have a dataset for which I need to re-label some items. Below I have a part of the code that looks at a certain value and then decides the final label. The whole dataset is approx 30000 lines long but it takes forever to complete this (simple?) task?

    I would be keen to understand why this is so slow as I need this type of loop coding for other queries as well.

    Thanks!

    Bundi

    
    Sub Update_data()
    
    ' 0. Variables
    ' ============
    
    ' Variables for loops
    Dim i As Long
    Dim viapoint As String
    
    ' 1. Computation
    ' ==============
    
    ' Desactivate display of Sheets during computation
    Application.ScreenUpdating = False
        
        'First dataline
        i = 2
        
        'Start Loop
        Do While Not IsEmpty(Cells(i, 1))
        
        'In loop variables
        viapoint = Cells(i, 4)
        
            ' Step 1 Flow
            
            Select Case viapoint
            
            Case "Direct traffic"
            
            Cells(i, 10) = "Direct"
            
            Case Else
            
            Cells(i, 10) = "Indirect"
            
            End Select
            
            i = i + 1
            
        Loop
        
        Application.ScreenUpdating = True
        End Sub

  2. #2
    Forum Expert
    Join Date
    12-14-2012
    Location
    London England
    MS-Off Ver
    MS 365 Office Suite.
    Posts
    8,448

    Re: Do while loop very slow?

    Your first issue is that you are using a loop.

    Never Ever Ever use a loop unless you really have to.

    If you really have no other option keep the code inside the loop to a minimum and limit the number of times the macro goes around the loop.

    Having said that I will now look at your code.



    So you are starting at row 2 and looping to the first empty row in column A


    You are looking at column D

    If D = "Direct traffic" then Column J ="Direct" oftherwise it is indirect

    Ok:

    The Formula for Cell J2 is
    Formula: copy to clipboard
    =IF(D2="Direct traffic","Direct", "Indirect")


    So I Paste that formula into cell J2, Start the Macro Recorder, Select Cell J2, click inside the formula bar and press enter.

    I then stop the macro recorder and look at the macro that it has recorded


    
    Sub Macro6()
    '
    ' Macro6 Macro
    '
    
    '
        Range("J2").Select
        ActiveCell.FormulaR1C1 = _
            "=IF(RC[-6]=""Direct traffic"",""Direct"", ""Indirect"")"
    End Sub

    Before I can go any further I need to find the Last row.

    So I need the line of code:

    LR = Cells(rows.count,1).End(xlUp).Row

    So I can now edit the recorded Macro to:


    
    Sub Macro6()
    
    LR = Cells(rows.count,1).End(xlUp).Row
    
    Range("J2:J" & LR).FormulaR1C1 = _
            "=IF(RC[-6]=""Direct traffic"",""Direct"", ""Indirect"")"
    
    Range("J2:J" & LR).value = Range("J2:J" & LR).value
    
    End Sub


    Try that.

    Instead of going around a loop 30000 times and performing 4 actions each time ie 120, 000 actions.

    I have achieved the same result using 3 Actions, Guess which solution is faster?
    Last edited by mehmetcik; 06-09-2018 at 03:14 PM.
    My General Rules if you want my help. Not aimed at any person in particular:

    1. Please Make Requests not demands, none of us get paid here.

    2. Check back on your post regularly. I will not return to a post after 4 days.
    If it is not important to you then it definitely is not important to me.

  3. #3
    Forum Guru
    Join Date
    09-10-2017
    Location
    Chippenham, England
    MS-Off Ver
    365
    Posts
    15,188

    Re: Do while loop very slow?

    As mehmetick said it's best to avoid loops where possible. Try
    Sub ReplaceLoop()
       With Range("J2:J" & Range("A" & Rows.Count).End(xlUp).row)
          .Value = Evaluate(Replace("If(@=""Direct traffic"",""Direct"",""Indirect"")", "@", .Offset(, -6).Address))
       End With
    End Sub

  4. #4
    Forum Expert
    Join Date
    10-06-2017
    Location
    drevni ruchadlo
    MS-Off Ver
    old
    Posts
    2,158

    Re: Do while loop very slow?

    Loops can also be quite fast ...

    2.5s to 3.0s for 60.000 rows, for a simple data system (see attachment):
    Sub Update_data_1()
    Dim i As Long: i = 2
    Dim valTime As Single: valTime = Timer
    
        Application.ScreenUpdating = False
        Application.Calculation = xlManual
        Do Until Cells(i, 1).Value = ""
            If Cells(i, 4).Value = "Direct traffic" Then Cells(i, 10).Value = "Direct" Else Cells(i, 10).Value = "Indirect"
            i = i + 1
        Loop
        Application.Calculation = xlAutomatic
        Application.ScreenUpdating = True
        MsgBox CStr(Timer - valTime)
    End Sub
    0.25s to 0.30s for 60.000 rows, for a simple data system (see attachment):
    Sub Update_data_2()
    Dim i As Long: i = Cells(Rows.Count, 1).End(xlUp).Row
    Dim uprbnd As Long: uprbnd = i - 1
    Dim valTime As Single: valTime = Timer
    Dim tbl()
    
        Application.ScreenUpdating = False
        Application.Calculation = xlManual
        tbl = Range("d2:d" & i).Value
        For i = 1 To uprbnd
            If tbl(i, 1) = "Direct traffic" Then tbl(i, 1) = "Direct" Else tbl(i, 1) = "Indirect"
        Next
        Range("j2:j" & i).Value = tbl
        Erase tbl
        Application.Calculation = xlAutomatic
        Application.ScreenUpdating = True
        MsgBox CStr(Timer - valTime)
    End Sub
    Attached Files Attached Files

  5. #5
    Forum Expert
    Join Date
    07-20-2011
    Location
    Mysore, India.
    MS-Off Ver
    Excel 2019
    Posts
    8,694

    Re: Do while loop very slow?

    Try this. It takes 1 sec for 650000 Rows


    Sub ReplaceAll()
     Application.ScreenUpdating = False
       
       With Range("J2:J" & Range("A" & Rows.Count).End(xlUp).Row)
          .Formula = "=If(D2=""Direct traffic"",""Direct"",""Indirect"")"
          .Value = .Value
       End With
    
     Application.ScreenUpdating = True
    End Sub
    Pl note
    Array formula should be confirmed with Ctrl+Shift+Enter keys together.
    If answere is satisfactory press * to add reputation.

  6. #6
    Forum Guru Kyle123's Avatar
    Join Date
    03-10-2010
    Location
    Leeds
    MS-Off Ver
    365 Win 11
    Posts
    7,238

    Re: Do while loop very slow?

    Not to nitpick on the above answers (though the solutions are indeed correct), but saying that loops are slow, or best avoided is touted frequently (though usually correctly) without context.

    There's nothing wrong or slow with loops per se, what are very slow however, are worksheet calls from VBA. Interactions with the worksheet are best done as infrequently as possible and in bulk, the reason that your code is slow is that you are looping through a worksheet range, and within each iteration of the loop performing several worksheet calls.

    In summary, the formula solutions above are fast, not specifically because they avoid looping, rather they avoid looping through the worksheet. Instead, they leverage Excel's native Formula engine that is much faster than accessing the worksheet object model through VBA.

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Loop running very slow
    By [email protected] in forum Excel Programming / VBA / Macros
    Replies: 6
    Last Post: 12-16-2017, 04:42 PM
  2. Alternative for slow loop
    By Jonathan78 in forum Excel Programming / VBA / Macros
    Replies: 10
    Last Post: 03-04-2016, 02:36 PM
  3. slow vba loop with arrays
    By danmcdon in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 08-16-2012, 10:55 PM
  4. For each loop very slow
    By CassioGodinho in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 04-02-2012, 04:50 PM
  5. Slow Do While Loop
    By bd528 in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 09-10-2010, 02:22 PM
  6. How do I slow down my loop ?
    By svanni in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 11-06-2006, 06:48 PM
  7. Loop running really slow...?
    By Buffyslay in forum Excel Programming / VBA / Macros
    Replies: 3
    Last Post: 06-26-2006, 09:40 AM

Bookmarks

Posting Permissions

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

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1