+ Reply to Thread
Page 6 of 12 FirstFirst ... 45678 ... LastLast
Results 76 to 90 of 167
  1. #76
    Forum Moderator DonkeyOte's Avatar
    Join Date
    10-22-2008
    Location
    Suffolk, UK
    MS-Off Ver
    2002, 2007 & 2010
    Posts
    21,379

    Re: What to Avoid in VBA

    Quote Originally Posted by JONvdHeyden View Post
    Regarding If, also apparently more efficient to use If...ElseIf...End If instead of Select Case.
    That arguably raises the delicate (?) issue of efficiency over practicality ...

    I'd nearly always opt for Select Case myself as I much prefer the structure and simplicity of syntax ... ordering of the Cases is of course important (and no Like allowed of course).

    In terms of efficiency over practicality I'd throw Evaluate into the mix as an alternative to Iteration (where viable).

    Bill Jelen (Excel Gurus Gone Wild) illustrates the potential performance variance using a simple example of inverting the sign of 100,000 cell values.
    Using a Loop this takes around 8 seconds whereas Evaluation takes less than a tenth of a second.
    (please note I'm not saying you would actually iterate to invert the values but still... it's a useful example)

    In reality compared to the most basic of Loop processes Evaluate is neither intuitive nor trivial to adapt [and as R has pointed out to me previously - needs to account for default Ref. Style]
    (you could probably argue the time spent setting it up would exceed the benefits gained at run time )

    So there should be some sort of trade off in IMO.... some practices are no brainers... other choices are not quite so clear cut, at least not for me.

    Sorry if I'm simply repeating prior comments...
    Last edited by DonkeyOte; 02-19-2010 at 11:54 AM.

  2. #77
    Forum Contributor
    Join Date
    04-16-2009
    Location
    Hampshire, UK
    MS-Off Ver
    Excel 2003; Excel 2007
    Posts
    134

    Re: What to Avoid in VBA

    Quote Originally Posted by DonkeyOte View Post
    In terms of efficiency over practicality I'd throw Evaluate into the mix as an alternative to Iteration (where viable).

    Bill Jelen (Excel Gurus Gone Wild) illustrates the potential performance variance using a simple example of inverting the sign of 100,000 cell values.
    Using a Loop this takes around 8 seconds whereas Evaluation takes less than a tenth of a second.
    Ah yes, I remember seeing this for the first time in one of your posts: http://www.excelforum.com/excel-gene...ork-sheet.html
    Regards

    Jon (Excel 2003, XP Pro)

  3. #78
    Forum Moderator romperstomper's Avatar
    Join Date
    11-04-2008
    Location
    Alibi
    MS-Off Ver
    All
    Posts
    8,262

    Re: What to Avoid in VBA

    I totally agree. If you were to code for pure performance, you would only ever use inline code rather than separate single-purpose subs/functions and maintaining it would be a nightmare!
    (of course if you wanted real performance you wouldn't be using VBA, but that's by-the-by.)
    So long, and thanks for all the fish.

  4. #79
    Forum Moderator Paul's Avatar
    Join Date
    02-05-2007
    Location
    Wisconsin
    MS-Off Ver
    2007
    Posts
    5,212

    Re: What to Avoid in VBA

    Hearing that If...ElseIf...Else is more efficient than Select Case is interesting, as every one of my programming teachers in college said the exact opposite. They're reasoning was that Select Case structures only check for the variable's value once and then perform each of the cases in order, whereas an If/ElseIf has to test it for every "case" as it were. If you have a Select Case with 20 cases and one variable test at the beginning vs If..ElseIf..Else with those same 20 tests done in order, one (ok, me) would think the Select Case is faster.

    Have I been led astray?!?

  5. #80
    Forum Moderator shg's Avatar
    Join Date
    06-21-2007
    Location
    The Great State of Texas
    MS-Off Ver
    2003, 2007
    Posts
    25,134

    Re: What to Avoid in VBA

    Regarding IIf: I use the structure frequently if the evaluation is trivial. Compactness and clarity have their own value:

    Code:
    sName = IIf(bFlag, "Bob", "Joe")

    I am never writing five lines of code to do that, or even this one:

    Code:
    If bFlag Then sName = "Bob" Else sName = "Joe"

    Re Case vs If:

    One of the first computers I programmed was an HP minicomputer in Fortran. The compiler had a toggle that would generate a mixed listing as output: Each line or two of Fortran was followed by the exact assembly code it generated. It taught me how to both write efficient Fortran and how to write in HP Assembler (... and how to write self-modifying code, but ignore that). To bad VBA doesn't do the same, even if the output were not assembler but whatever virtual machine code the compiler uses.

    And all that said, I use Select Case in preference to If/ElseIf unless I really feel it's important. It's more visually apparent.

    Quote Originally Posted by StephenR
    5. Always indent your code properly.
    Stephen, I couldn't agree more. It makes program flow much more apparent, and makes orderly code look orderly, which is one of the nicest gifts you can give yourself or the other poor dog that picks up your code a year later.
    Last edited by shg; 02-19-2010 at 01:46 PM.
    Microsoft MVP - Excel
    Entia non sunt multiplicanda sine necessitate

  6. #81
    Forum Guru
    Join Date
    01-03-2006
    Location
    Basingstoke, England
    MS-Off Ver
    2007 (work & home)
    Posts
    2,240

    Re: What to Avoid in VBA

    Where is the sub-quoted section of Stephen's when I try to "Quote" the Shg's last post?
    Is this a known issue...?
    (I think I'll add it to the feedback thread & see what happens )

    Quote Originally Posted by shg View Post
    ...
    Insert: no sign of Stephen's subquote?
    Stephen, I couldn't agree more. It makes program flow much more apparent, and makes orderly code look orderly, which is one of the nicest gifts you can give yourself or the other poor dog that picks up your code a year later.
    Yep, me too & I haven't had much chance to gift my work to others... yet! ;-)
    I try to run people's code through Bovey's smart indenter.xla before posting, whenever the code is of reasonable length/levels. When I can see people are really keen to learn (& I remember) I suggest Smart Indenter, Code Cleaner & MZ Tools (esp after RS pointing out some extra tricks that it contains).
    Rob Brockett
    Kiwi in the UK
    Always learning & the best way to learn is to experience...

  7. #82
    Forum Guru
    Join Date
    08-26-2007
    Location
    London
    Posts
    3,714

    Re: What to Avoid in VBA

    Thanks shg, but I merely collated the list from others' contributions. However, I do observe that stricture. The aesthetics of VBA is a much overlooked topic...

  8. #83
    Forum Moderator romperstomper's Avatar
    Join Date
    11-04-2008
    Location
    Alibi
    MS-Off Ver
    All
    Posts
    8,262

    Re: What to Avoid in VBA

    I think with many of these things, the old adage about theory and practice comes into play!
    So long, and thanks for all the fish.

  9. #84
    Forum Moderator shg's Avatar
    Join Date
    06-21-2007
    Location
    The Great State of Texas
    MS-Off Ver
    2003, 2007
    Posts
    25,134

    Re: What to Avoid in VBA

    IMO, it's like playing bridge; play third-hand high, and return your partner's leads, until you clearly understand why not to on any given occasion.
    Microsoft MVP - Excel
    Entia non sunt multiplicanda sine necessitate

  10. #85
    Valued Forum Contributor tony h's Avatar
    Join Date
    03-14-2005
    Location
    England: London and Lincolnshire
    Posts
    768

    Re: What to Avoid in VBA

    Learn to use the :
    - debug tools especially F8
    - the object browser
    - help

    and when nameing variables think about how they will read eg:
    not
    Code:
        bReset = TRUE        'does this mean the reset has been done or need to do a reset
           if bReset then
    but either of
    Code:
        bIsReset = TRUE
           if bIsReset then
    
        bDoReset = TRUE
           if bDoReset then


    Hope this was useful or entertaining.

  11. #86
    Forum Contributor pierre08's Avatar
    Join Date
    02-16-2010
    Location
    Paris
    MS-Off Ver
    Excel 2003
    Posts
    164

    Re: What to Avoid in VBA

    I think it's complet, i don't think that there are any missing point in this:

    Quote Originally Posted by StephenR View Post
    1. Wherever you see several lines lines of very similar code look for the common bits and consider how you can use a variable (e.g. a loop counter) and cut out all the common lines.
    2. Use small procedures for one specific task only and link them from a main 'Control' procedure. Don't keep adding lines of code to a procedure just because you can.
    3. Don't Loop when you can filter.
    4. Use Error Handling so your code exits gracefully when needed.
    5. Always indent your code properly.
    6. Apply and use a naming convention consistently (e.g variable declarations).
    7. Use sheet CodeName when ever possible, instead of Name or Index.
    8. Use Early Binding (some exceptions to this rule).
    9. Explicitly use ByRef or ByVal if a procedure takes arguments.
    10. Avoid Option Compare Text.
    11. Use class modules for global variables.
    12. If you have a non-general error trap (ie a condition where an error is expected) put that specific code in a submodule or function.
    13. Use descriptive variable names (with possible exception of transient local variables).
    14. Keep scoping as local as possible with prefixes to identify the scope as well as variable type.
    15. Declare all variables appropriate to usage.
    16. Use Variants only when necessary ((i) To receive an argument that may be of varying type (string, Boolean, number, or arrays of same); (ii) To receive a value from a cell than may be of varying type; (iii) To receive the value of a multi-cell range from a worksheet; (iv) To receive an indefinite number of arguments (ParamArray is a variant); (v) To receive the results from many worksheet functions, like MMult and Array; (vi) To receive the value of a property that may return Null; (vii) To receive the keys of a dictionary; (viii) To be the control variable of a For Each loop when not a more closely-aligned data type is available (e.g., a Range); (ix) To be the return type of a function that returns data of varying type, or (on Mac) an array of variable size).
    17. Don’t select cells, sheets, workbooks, or other objects except as necessary.
    18. Generally, use built-in (worksheet) functions when possible (there are some exceptions).
    19. Don’t use loops if there’s a way around it; if there isn’t, prefer iterating elements from a collection (For Each/Next), followed by For/Next and Do/Loop.
    20. Select Case statements are prettier, If/ElseIf/Else/EndIf statements are faster. Either should be arranged to test cases from most likely to least.
    21. Use collections and dictionaries in preference to other data structures when possible, and use dictionaries instead of collections, unless ordering is required.
    22. Use the Like operator sparingly. Ditto for Regular Expressions. Avoid text comparison entirely when there are other options (e.g., TypeOf versus TypeName).
    23. The Len function is among Excel's fastest; all it has to do is grab the first word of a string, where the length is stored. So rather than If s <> "", use If Len(s) (and there’s no need to coerce a number to a Boolean so it can be converted back to a number).
    24. Write logical, clear code first, and then optimize for speed. Don’t obscure the structure and intent of code for speed unless you don’t mind having the person that has to maintain it later casting aspersions on your lineage.
    25. Comment your code minimally beyond the procedure level; it’s impossible to keep code and comments in sync. Instead, make code shine in clarity and simplicity.
    26. Set Calculation to manual during execution. If worksheet calculation is necessary in the course of macro execution, calculate only the minimum range necessary.
    27. Turn off ScreenUpdating during execution.
    28. Turn off events if necessary to avoid triggering change event macros and getting other listeners excited.
    29. And use dictionaries instead of collections, unless ordering is required.
    30. Don't use IIf.
    31. Don't compare Boolean variables explicitly to True/False - it serves no purpose. .

    What i want to add is just this, it turn off Evrything but the Essentials while your Code is Runnig, doing this should help improve the performance of your code:
    Code:
    'Get current state of various Excel settings; put this at the beginning of your code
    
    screenUpdateState = Application.ScreenUpdating
    statusBarState = Application.DisplayStatusBar
    calcState = Application.Calculation
    eventsState = Application.EnableEvents
    displayPageBreakState = ActiveSheet.DisplayPageBreaks 'note this is a sheet-level setting
    
    'turn off some Excel functionality so your code runs faster
    
    Application.ScreenUpdating = False
    Application.DisplayStatusBar = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False
    ActiveSheet.DisplayPageBreaks = False 'note this is a sheet-level setting
    
    '>>your code goes here<<
    'after your code runs, restore state; put this at the end of your code
    
    Application.ScreenUpdating = screenUpdateState
    Application.DisplayStatusBar = statusBarState
    Application.Calculation = calcState
    Application.EnableEvents = eventsState
    ActiveSheet.DisplayPageBreaks = displayPageBreaksState 'note this is a sheet-level setting
    From http://blogs.msdn.com/excel/archive/...practices.aspx

    What do you think we should add to this to have a complet page of all the things that we should avoid in Vba

  12. #87
    Forum Guru Domski's Avatar
    Join Date
    12-14-2009
    Location
    Leeds, UK
    MS-Off Ver
    2003 (work), 2007 & 2010 (home)
    Posts
    3,517

    Re: What to Avoid in VBA

    Something else just thought of...

    If replacing formula with values rather than use copy...paste special...values use .value = .value e.g.:

    Code:
    With Range("A1:A10")
    
        .Value = .Value
        
    End With
    Dom
    "May the fleas of a thousand camels infest the crotch of the person who screws up your day and may their arms be too short to scratch..."

    If you haven't already please take some time to read the Forum Rules.

    Use code tags when posting your VBA code: [code] Your code here [/code]

    Remember, saying thanks only takes a second or two. Click the little star to give some Rep if you think an answer deserves it.

  13. #88
    Forum Guru JBeaucaire's Avatar
    Join Date
    03-21-2008
    Location
    Bakersfield, CA
    MS-Off Ver
    2010
    Posts
    18,228

    Re: What to Avoid in VBA

    Code:
    .value = .value
    This is one of my favorite tricks to use. Any arguments against it?
    _________________
    Microsoft MVP 2010 - Excel
    Visit: Jerry Beaucaire's Excel Files & Macros

    If you've been given good help, use the icon below to give reputation feedback, it is appreciated.
    Always put your code between code tags. [CODE] your code here [/CODE]

    “None of us is as good as all of us” - Ray Kroc
    “Actually, I *am* a rocket scientist.” - JB (little ones count!)

  14. #89
    Forum Guru
    Join Date
    08-26-2007
    Location
    London
    Posts
    3,714

    Re: What to Avoid in VBA

    I use it too, but what is the argument for it? Is it quicker?

  15. #90
    Forum Guru Domski's Avatar
    Join Date
    12-14-2009
    Location
    Leeds, UK
    MS-Off Ver
    2003 (work), 2007 & 2010 (home)
    Posts
    3,517

    Re: What to Avoid in VBA

    I remember seeing a discussion about it on Mr Excel which I'm sure suggested it should be used in preference to paste special.

    I'll see if I can find it and post the link.

    Dom
    "May the fleas of a thousand camels infest the crotch of the person who screws up your day and may their arms be too short to scratch..."

    If you haven't already please take some time to read the Forum Rules.

    Use code tags when posting your VBA code: [code] Your code here [/code]

    Remember, saying thanks only takes a second or two. Click the little star to give some Rep if you think an answer deserves it.

Thread Information

Users Browsing this Thread

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

Tags for this Thread

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.2.0