+ Reply to Thread
Page 4 of 12 FirstFirst ... 23456 ... LastLast
Results 46 to 60 of 167

Thread: What to Avoid in VBA

  1. #46
    Cheeky Forum Moderator Ron Coderre's Avatar
    Join Date
    03-22-2005
    Location
    Boston, Massachusetts
    MS-Off Ver
    2003, 2007, 2010
    Posts
    3,712

    Re: What to Avoid in VBA

    I stand by my recommendation.
    Using "For i = j to k" is ok for homework, but is a bad habit to get into for production work.
    ALWAYS assume your little bit of code will be built upon, expanded, or become part of a larger project. A few seconds spent up front could save hours later.

    I've had to clean up too many instances of other people's code that was like this:
    For i = j to k Step p
        For x = y to z
            If a > b Then
                '....many lines of code
            Else
                '....many lines of code
            End If
        Next
    Next
    50 lines into the code, my head is spinning when I run into a line like:
    "If i < z Then"
    Regards,

    Ron
    Microsoft MVP - Excel
    (Oct 2006 - Sep 2012)

    Click here to see the Forum Rules

  2. #47
    Forum Guru Andy Pope's Avatar
    Join Date
    05-10-2004
    Location
    Essex, UK
    MS-Off Ver
    2003 & 2007 & 2010
    Posts
    11,351

    Re: What to Avoid in VBA

    I see. You still have a global variable but it's more obvious and with centralised control over possible bad states.

    For scoping I keep it as local as possible with prefixes to identify the scope as well as variable type.

    
    strA        ' local to routine
    m_strA    ' local to module
    g_strA     ' local to project
    Cheers
    Andy
    www.andypope.info

  3. #48
    Forum Guru rwgrietveld's Avatar
    Join Date
    09-02-2008
    Location
    Netherlands
    MS-Off Ver
    XL 2007 / XL 2010
    Posts
    1,671

    Re: What to Avoid in VBA

    I agree with you that using some sort of notation like the hungarian notation would help maintain (and understand) the code.

    ... and do we now ALL promise to use this in our Forum answers ? or do we consider that as homework?
    Looking for great solutions but hate waiting?
    Seach this Forum through Google

    www.Google.com
    (e.g. +multiple +IF site:excelforum.com/excel-general/ )

    www.Google.com
    (e.g. +fill +combobox site:excelforum.com/excel-programming/ )

    Ave,
    Ricardo

  4. #49
    Forum Guru Domski's Avatar
    Join Date
    12-14-2009
    MS-Off Ver
    What does it matter?
    Posts
    3,933

    Re: What to Avoid in VBA

    It's homework until I get my honorary doctorate from the University of Excel!!!

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

    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.

  5. #50
    Cheeky Forum Moderator Ron Coderre's Avatar
    Join Date
    03-22-2005
    Location
    Boston, Massachusetts
    MS-Off Ver
    2003, 2007, 2010
    Posts
    3,712

    Re: What to Avoid in VBA

    I agree to continue using descriptive variables in posts.

    In our responses, we are teaching proper methods for solving Excel issues.

    While inefficiencies in formatting, functions, and sheet structure are usuallly easy to correct,
    poor programming habits in small projects turn into poor programming in large projects
    that can be a nightmare to fix. Best to prevent them at the beginning.
    Regards,

    Ron
    Microsoft MVP - Excel
    (Oct 2006 - Sep 2012)

    Click here to see the Forum Rules

  6. #51
    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

    Quote Originally Posted by RichardSchollar View Post
    I bet you wouldn't really use a variable named "str", Tony
    Hmmm

        str = str & " where c2.IsReal=""Y"" and [c2].[Include] = true " 'don't include non partners
        Set rstAllPartners = db.OpenRecordset(str)
        IsFirstPass = True
    But you see it is only useful very locally (in this case for one line). Sometimes it takes several lines to compile the select statement.



    Hope this was useful or entertaining.

  7. #52
    Forum Guru romperstomper's Avatar
    Join Date
    11-04-2008
    Location
    Apparently I can't say
    MS-Off Ver
    Apparently I can't say
    Posts
    8,274

    Re: What to Avoid in VBA

    I think Richard was referring to the fact that str is a native VBA function...

  8. #53
    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

    Quote Originally Posted by tony h View Post
    There are a number of advantages (in my mind). By using a class module I tend to call it myGlobals and using properties then:
    1. it is quite clear that you are using a global value as the syntax is myglobl.TaxRrate
    2. it is easy to trap where the global is used as you can put a breakpoint on the property in the class module
    3. when dealing with anything that can go out of scope or lose connectivity (eg connecting to databases especially when updating a spreadsheet) it is easy for the DB objects to be outof scope. By using the myGlobals class the error trapping can be done and the reinstating of the connection effectively automatically by keeping all the code in one place.
    4. This also helps with creating logfiles.

    and probably a few more

    5. and usng the class terminate you can ensure a proper close down of connections
    6. which is also a good way of trapping unexpected "out of scope" conditions.


    Hope this was useful or entertaining.

  9. #54
    Forum Guru shg's Avatar
    Join Date
    06-20-2007
    Location
    The Great State of Texas
    MS-Off Ver
    2003, 2007, 2010
    Posts
    25,777

    Re: What to Avoid in VBA

    Quote Originally Posted by David
    Range.Replace.

    If you do find or replace Within Workbook outside of VBA, then run range.replace in VBA, it replaces in whole workbook.
    Quote Originally Posted by Dom
    I was told when using Find and Replace in VBA it's a good idea to specify all the arguments every time. Not doing so can cause problems similar to what you have eluded to.
    The error occurs when you do a Replace across the workbook (from the UI, per force), then a range.Replace from VBA. The range is ignored and replacement is performed throughout the workbook. Specifying all the parameters of the Replace won't help; you have to do a dummy Find to reset the behavior:

    Set r = Worksheets(1).Range("A1").Find(What:="Texas", LookIn:=xlFormulas)
    The word Texas is key here ...

    Don't know if this has been corrected.

    Here's my list:
    1) Variables
    
        a) Pick a variable naming convention and follow it. 
    
        b) Declare all variables appropriate to usage. 
    
        c) Use Variants only when necessary, to wit:
    
            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 (I'd have 
                 thought that a dynamic array of Doubles would work, but I couldn't get it to)
                 and Array
    
            vi)  To receive the value of a property that may return Null 
                 (e.g., Selection.Interior.ColorIndex for a non-homogeneous selection)
    
            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, I’m told) an array of variable size 
    
    2) Don’t select cells, sheets, workbooks, or other objects except as necessary
    
    3) Code structures:
    
        a) Generally, use built-in (worksheet) functions when possible
           (there are some exceptions).
    
        b) 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. 
    
        c) Select Case statements are prettier, If/ElseIf/Else/EndIf statements are faster (curious; you'd think the compiled code would be the same). Either should be arranged to test cases from most likely to least.
    
        d) Use collections and dictionaries in preference to other data structures when possible.
    
        e) Don't use Option Compare Text; there are better options. 
    
        f) Use the Like operator sparingly. Ditto for Regular Expressions. Avoid text comparison entirely when there are other options (e.g., TypeOf  versus TypeName)
    
        g) 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)
    
        h) Use early binding for objects unless you have specific reason not to.
    
        i) 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.
    
        j) 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.
    
    4) Speed
    
        a) Set Calculation to manual during execution. If worksheet calculation is necessary 
           in the course of macro execution, calculate only the minimum range necessary.
    
        b) Turn off ScreenUpdating during execution
    
        c) Turn off events if necessary to avoid triggering change event macros and getting 
           other listeners excited
    Microsoft MVP - Excel
    Entia non sunt multiplicanda sine necessitate

  10. #55
    Forum Guru
    Join Date
    01-03-2006
    Location
    Taranaki, New Zealand
    MS-Off Ver
    2007 (work & home)
    Posts
    2,242

    Re: What to Avoid in VBA



    This thread has started humming since I last saw it!

    Shg, I can't remember having ever seen a code snippet on the Forum that uses TypeName or VarType etc & I'm going to have go investigating now!

    I may have missed this in amongst the posts, but what is the general consensus on explicitly naming arguments vs using commas as placeholders in argument listings?
    For example:
    MsgBox "done", , "FINISHED"
    MsgBox prompt:="done", Title:="FINISHED"
    I try for the latter, but I know I'm guilty of the former, & it's usually when I can see the OP is likely to have some understanding of the code already. In other words, I'm probably reinforcing existing bad habits & showing the new folk to "do as I say rather than do as I really do"...

    Rob
    Rob Brockett
    Kiwi in the UK
    Always learning & the best way to learn is to experience...

  11. #56
    Forum Guru
    Join Date
    08-26-2007
    Location
    London
    Posts
    3,788

    Re: What to Avoid in VBA

    shg: as articulate as ever. It's always a pleasure to read your posts. I wonder if you might expand on your reasoning behind
    prefer iterating elements from a collection (For Each/Next), followed by For/Next and Do/Loop.
    and
    Use the Like operator sparingly. Ditto for Regular Expressions.
    broro183: fwiw, I'm inconsistent. With Find I explicitly name the arguments I specify (not necessarily all of them), but for Copy/Paste I never specify Destination. I suppose good practice would be to name them all, but I think given most of us have limited time on the forum we tend to cut corners. I have to confess that I am probably more thorough when writing code for my own use.

  12. #57
    Forum Guru romperstomper's Avatar
    Join Date
    11-04-2008
    Location
    Apparently I can't say
    MS-Off Ver
    Apparently I can't say
    Posts
    8,274

    Re: What to Avoid in VBA

    Just be aware that TypeOf and TypeName don't do the same thing and TypeName is better in certain situations.

  13. #58
    Forum Guru shg's Avatar
    Join Date
    06-20-2007
    Location
    The Great State of Texas
    MS-Off Ver
    2003, 2007, 2010
    Posts
    25,777

    Re: What to Avoid in VBA

    Just be aware that TypeOf and TypeName don't do the same thing and TypeName is better in certain situations.
    Indeed, and I believe you gave me an good example with controls some weeks ago.

    Maybe this is a better example of avoiding a text comparison:
        Set wks = Worksheets("Sheet1")
        If wks Is Sheet1 Then MsgBox "True"         ' is better IMO than
        If wks.CodeName = "Sheet1" Then MsgBox "True"
    Last edited by shg; 02-18-2010 at 05:30 PM.
    Microsoft MVP - Excel
    Entia non sunt multiplicanda sine necessitate

  14. #59
    Forum Guru
    Join Date
    01-03-2006
    Location
    Taranaki, New Zealand
    MS-Off Ver
    2007 (work & home)
    Posts
    2,242

    Re: What to Avoid in VBA

    Thanks Shg & RS,
    "TypeOf" is my little learning for today - it seems to be hidden away in the 2007 Help files under "If...Then...Else Statement".

    My investigations/Google shows an incy squincy total of about 100 results in the Forum for the below three data information functions: http://www.google.co.uk/search?hl=en...meta=&aq=f&oq=
    Could/should we be more defensive when offering solutions?

    StephenR, I'm pleased I'm not the only inconsistent one - your logic is sound too.
    Rob Brockett
    Kiwi in the UK
    Always learning & the best way to learn is to experience...

  15. #60
    Forum Guru shg's Avatar
    Join Date
    06-20-2007
    Location
    The Great State of Texas
    MS-Off Ver
    2003, 2007, 2010
    Posts
    25,777

    Re: What to Avoid in VBA

    expand on your reasoning behind

    prefer iterating elements from a collection (For Each/Next), followed by For/Next and Do/Loop.
    and

    Use the Like operator sparingly. Ditto for Regular Expressions.
    My understanding is that iteration and search of collections and dictionaries are very fast and highly optimized. They are also very intuitive stuctures, IMO. Beats the heck out of redimensioning dynamic arrays in a loop.

    RegEx and it's little brother, the Like operator, entail complex comparisons; think about the difficulty of writing one, and then stop when you feel a blood vessel approaching the bursting point in your brain. They're great tools, just limit their use to when they are justified.

    Like is so easy to use that I abuse it, I confess.
    Last edited by shg; 02-18-2010 at 05:31 PM.
    Microsoft MVP - Excel
    Entia non sunt multiplicanda sine necessitate

+ Reply to Thread

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