Consulting

Results 1 to 6 of 6

Thread: How to speed up loop

  1. #1

    How to speed up loop

    The following code works, albeit slowly. Any tips on speeding it up? I'm guessing there must be a way to establish a smaller, discontiguous range that only includes cells that contain data and/or have been formatted.
    [vba]Sub ColorLoop()

    Dim cel As Range
    Dim myWorksheet As Range

    Set myWorksheet = Range("A1:IV65536")

    For Each cel In myWorksheet
    If cel.Font.ColorIndex = 5 Then
    cel.Interior.ColorIndex = 36
    End If
    Next cel

    End Sub
    [/vba]

  2. #2
    VBAX Master
    Joined
    Jun 2007
    Location
    East Sussex
    Posts
    1,110
    Location
    You could change this:
    Set myWorksheet = Range("A1:IV65536")
    to this:
    Set myWorksheet = ActiveSheet.UsedRange

    Regards,
    Rory
    Regards,
    Rory

    Microsoft MVP - Excel

  3. #3
    Works like a charm. Thanks for introducing me to UsedRange--it will come in handy.

  4. #4
    VBAX Master
    Joined
    Jun 2007
    Location
    East Sussex
    Posts
    1,110
    Location
    You're welcome. You should just be aware that UsedRange is not always what you think it ought to be (Excel sometimes stubbornly remembers ranges that have had formatting applied as still being 'used') but for these purposes it is better than specifying every cell on the worksheet!
    Regards,
    Rory

    Microsoft MVP - Excel

  5. #5
    Administrator
    VP-Knowledge Base
    VBAX Grand Master mdmackillop's Avatar
    Joined
    May 2004
    Location
    Scotland
    Posts
    14,489
    Location
    Also check out SpecialCells which you can use to ignore blanks etc.
    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'

  6. #6
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    Quote Originally Posted by rory
    You're welcome. You should just be aware that UsedRange is not always what you think it ought to be (Excel sometimes stubbornly remembers ranges that have had formatting applied as still being 'used') but for these purposes it is better than specifying every cell on the worksheet!
    But easily sorted http://www.contextures.com/xlfaqApp.html#Unused
    ____________________________________________
    Nihil simul inventum est et perfectum

    Abusus non tollit usum

    Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I've not seen!
    James Thurber

Posting Permissions

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