Consulting

Results 1 to 19 of 19

Thread: To declare or not to declare

  1. #1
    Administrator VBAX Master georgiboy's Avatar
    Joined
    Mar 2008
    Location
    Kent, England
    Posts
    1,256
    Location

    Question To declare or not to declare

    Hi everyone,

    I intend this thread to be a general discussion on the topic of variable declaration.

    I’m interested in hearing your personal opinions on whether or not to declare variables. Please share your experiences and provide arguments for and against variable declaration, along with examples if possible.

    I’m not looking for a definitive answer on whether we should declare variables, as I understand this is largely a matter of personal style. Instead, I hope this discussion will offer insights that help others decide whether variable declaration aligns with their coding style.

    Personally, I believe in declaring variables, and here are a few reasons why. I may post some examples later in the thread:

    • Memory Management: By specifying the data type, VBA allocates the right amount of memory for the variable.
    • Code Readability: Well named variables make your code easier to understand.
    • Error Checking: Declaring variables helps catch errors where a variable might be used incorrectly.
    • Optimization: The VBA compiler can optimize the code better if it knows the data types in advance.

    REMEMBER, this is a discussion and not an argument so play nice.

    Have a nice day...

    George
    Click here for a guide on how to add code tags
    Click here for a guide on how to mark a thread as solved
    Click here for a guide on how to upload a file with your post

    Excel 365, Version 2408, Build 17928.20080

  2. #2
    VBAX Master Aflatoon's Avatar
    Joined
    Sep 2009
    Location
    UK
    Posts
    1,779
    Location
    Devil's advocate:
    Memory management: is irrelevant in pretty much all code that I've seen in forums.
    Code readability: doesn't actually require you to declare your variables. Also, variable naming and where to declare is a whole other flame war.
    Error checking: can also give a false sense of security as the compiler isn't necessarily 100% reliable on that front
    Optimisation: see memory management

    Against declaring:
    Saves typing and therefore reduces the risk of RSI and/or arthritis in later life

    I'm not sure I've ever seen any other arguments against it.
    Be as you wish to seem

  3. #3
    Moderator VBAX Wizard Aussiebear's Avatar
    Joined
    Dec 2005
    Location
    Queensland
    Posts
    5,234
    Location
    I am a firm believer in declaring your variables. Keeps your code tidy and readable, more so if the code become the responsibility of someone else to maintain it. For those prolific writers of code, it enables you to remember what your code is representing months down the track.
    Remember To Do the Following....
    Use [Code].... [/Code] tags when posting code to the thread.
    Mark your thread as Solved if satisfied by using the Thread Tools options.
    If posting the same issue to another forum please show the link

  4. #4
    VBAX Expert
    Joined
    Aug 2004
    Posts
    812
    Location
    I declare my variables for the purpose of error checking (primarily). I had my misses in the past and cost me dearly.

  5. #5
    VBAX Sage
    Joined
    Apr 2007
    Location
    United States
    Posts
    8,787
    Location
    My $0.02 ---

    If a variable is not declared, then it's a Variant, which means anything can be assigned or assigned again

    I prefer to get a runtime or development time error since I want all the help I can get

    'Option Explicit
    
    Sub NotDelcared()
        x = 1234
        x = "asdfg"
        x = True
        Set x = Worksheets(1)
        MsgBox x.Name
    End Sub
    
    
    Sub Delcared()
        Dim n As Long
        Dim s As String
        Dim b As Boolean
        Dim o As Worksheet
        n = 1234
        s = "asdfg"
        b = True
        Set o = Worksheets(1)
        MsgBox o.Name
        n = s
    End Sub
    Capture.JPG
    Last edited by Paul_Hossler; 05-17-2024 at 08:07 AM.
    ---------------------------------------------------------------------------------------------------------------------

    Paul


    Remember: Tell us WHAT you want to do, not HOW you think you want to do it

    1. Use [CODE] ....[/CODE ] Tags for readability
    [CODE]PasteYourCodeHere[/CODE ] -- (or paste your code, select it, click [#] button)
    2. Upload an example
    Go Advanced / Attachments - Manage Attachments / Add Files / Select Files / Select the file(s) / Upload Files / Done
    3. Mark the thread as [Solved] when you have an answer
    Thread Tools (on the top right corner, above the first message)
    4. Read the Forum FAQ, especially the part about cross-posting in other forums
    http://www.vbaexpress.com/forum/faq...._new_faq_item3

  6. #6
    Administrator VBAX Master georgiboy's Avatar
    Joined
    Mar 2008
    Location
    Kent, England
    Posts
    1,256
    Location
    I have to agree on that part @Paul_Hossler,

    In my experience, I am able to capture errors earlier in the code and (to me) they make more sense as to where the errors form. Take the below for example, without declarations the error forms on the last line and (again, to me) does not seem completely obvious as to why:
    Sub NotDeclared()    
        s = "Hello world"
        
        ' some code...
        
        n = s
        
        ' Lots and
        ' lots and
        ' lots of code
        
        MsgBox n + 1 '<<< Error comes here
    End Sub
    Whereas with the variables being declared (below), the error comes much earlier in the code and seems (to me) more obvious as to what the problem is as it comes when passing a value to a variable. Worth noting also that the error was triggered before the 'Lots of code' part, so if you are into writing long sub routines then it could save you some scrolling up and down:
    Sub Declared()
        Dim s As String, n As Long
        
        s = "Hello world"
        
        ' some code...
        
        n = s  '<<< Error comes here
        
        ' Lots and
        ' lots and
        ' lots of code
        
        MsgBox n + 1
    End Sub
    I would still like to see some arguments for not declaring as I am sure there are some logical arguments and thought processes behind both methods.
    Click here for a guide on how to add code tags
    Click here for a guide on how to mark a thread as solved
    Click here for a guide on how to upload a file with your post

    Excel 365, Version 2408, Build 17928.20080

  7. #7
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,446
    Location
    I am very pro declaring variables, and adding Option Explicit to all modules.

    Rory's arguments, Devil's advocate I know, but for, even if the compiler is not 100% accurate, surely it is better to get whatever comfort it does provide. And you can also get extra comfort when using the variable, I declare the name with a form of camel-case, but type them in lower-case. If I type it correctly, it upshifts, if I don't I get an immediate feedback that I have erred. Against, the extra typing is totally irrelevant in my eyes, we don't write enough code to make declaring variables onerous. You can save later when you use a variable by typing a few letters, then use Ctl-spacebar to auto-complete.

    Bill Jelen doesn't believe Option Explicit, he and I have had this discussion so often. but I haven't convinced him.
    ____________________________________________
    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

  8. #8
    VBAX Master Aflatoon's Avatar
    Joined
    Sep 2009
    Location
    UK
    Posts
    1,779
    Location
    For the record, I always declare. Even as lazy as I am, I can’t see any benefit to not doing so; and there are definite benefits to doing it, as everyone has mentioned.

    still waiting for a certain someone to show up in this thread…
    Be as you wish to seem

  9. #9
    Moderator VBAX Wizard Aussiebear's Avatar
    Joined
    Dec 2005
    Location
    Queensland
    Posts
    5,234
    Location
    I doubt if he will....
    Remember To Do the Following....
    Use [Code].... [/Code] tags when posting code to the thread.
    Mark your thread as Solved if satisfied by using the Thread Tools options.
    If posting the same issue to another forum please show the link

  10. #10
    BoardCoder
    Licensed Coder
    VBAX Expert mark007's Avatar
    Joined
    May 2004
    Location
    Leeds, UK
    Posts
    620
    Location
    Surely you all have 'Require variable declaration' ticked to force it!


    Dim ImportantValue as string
    ImportantValue="Important"
    
    
    If ImpotantValue="" then
        Msgbox "Why have I spent hours debugging this code to find out why this message keeps appearing?"
    end if
    "Computers are useless. They can only give you answers." - Pablo Picasso
    Mark Rowlinson FIA | The Code Net

  11. #11
    Moderator VBAX Wizard Aussiebear's Avatar
    Joined
    Dec 2005
    Location
    Queensland
    Posts
    5,234
    Location
    Quote Originally Posted by mark007 View Post
    Surely you all have 'Require variable declaration' ticked to force it!
    True, but you need to want to do this.
    Remember To Do the Following....
    Use [Code].... [/Code] tags when posting code to the thread.
    Mark your thread as Solved if satisfied by using the Thread Tools options.
    If posting the same issue to another forum please show the link

  12. #12
    Declaring actually SAVES typing. Especially if a variable is used more than once or twice: type one or two characters, hit control+Space and bam! And declaring vairables using the correct type allows intellisense to work.
    Regards,

    Jan Karel Pieterse
    Excel MVP jkp-ads.com

  13. #13
    Administrator VBAX Master georgiboy's Avatar
    Joined
    Mar 2008
    Location
    Kent, England
    Posts
    1,256
    Location
    Quote Originally Posted by Jan Karel Pieterse View Post
    declaring vairables using the correct type allows intellisense to work.
    This is a good point, saves even more typing.

  14. #14
    Moderator VBAX Wizard Aussiebear's Avatar
    Joined
    Dec 2005
    Location
    Queensland
    Posts
    5,234
    Location
    Right so at this stage, its 99.9% in favour of declaring and 0.1% as not declaring. Mind you the 0.1% is for the guy who thinks its not necessary but couldn't find the courage to post.
    Remember To Do the Following....
    Use [Code].... [/Code] tags when posting code to the thread.
    Mark your thread as Solved if satisfied by using the Thread Tools options.
    If posting the same issue to another forum please show the link

  15. #15
    VBAX Master Aflatoon's Avatar
    Joined
    Sep 2009
    Location
    UK
    Posts
    1,779
    Location
    Quote Originally Posted by Jan Karel Pieterse View Post
    Declaring actually SAVES typing. Especially if a variable is used more than once or twice: type one or two characters, hit control+Space and bam!
    Not if you also only ever use 1-3 characters for your variable names...
    Be as you wish to seem

  16. #16
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,446
    Location
    Quote Originally Posted by Aflatoon View Post
    Not if you also only ever use 1-3 characters for your variable names...
    Many moons ago, in my days as a Cobol programmer, a colleague would declare their variables as a,b,c,d, etc. Drove me mad.
    ____________________________________________
    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

  17. #17
    Moderator VBAX Wizard Aussiebear's Avatar
    Joined
    Dec 2005
    Location
    Queensland
    Posts
    5,234
    Location
    Quote Originally Posted by Bob Phillips View Post
    Many moons ago, in my days as a Cobol programmer, a colleague would declare their variables as a,b,c,d, etc. Drove me mad.
    oooookay...... !!!!

    On second thoughts, you are not mad, just English.
    Remember To Do the Following....
    Use [Code].... [/Code] tags when posting code to the thread.
    Mark your thread as Solved if satisfied by using the Thread Tools options.
    If posting the same issue to another forum please show the link

  18. #18
    VBAX Sage
    Joined
    Apr 2007
    Location
    United States
    Posts
    8,787
    Location
    Quote Originally Posted by Bob Phillips View Post
    Many moons ago, in my days as a Cobol programmer, a colleague would declare their variables as a,b,c,d, etc. Drove me mad.
    How about aa, a1, a_1, _a, _a1, ...
    ---------------------------------------------------------------------------------------------------------------------

    Paul


    Remember: Tell us WHAT you want to do, not HOW you think you want to do it

    1. Use [CODE] ....[/CODE ] Tags for readability
    [CODE]PasteYourCodeHere[/CODE ] -- (or paste your code, select it, click [#] button)
    2. Upload an example
    Go Advanced / Attachments - Manage Attachments / Add Files / Select Files / Select the file(s) / Upload Files / Done
    3. Mark the thread as [Solved] when you have an answer
    Thread Tools (on the top right corner, above the first message)
    4. Read the Forum FAQ, especially the part about cross-posting in other forums
    http://www.vbaexpress.com/forum/faq...._new_faq_item3

  19. #19
    Moderator VBAX Wizard Aussiebear's Avatar
    Joined
    Dec 2005
    Location
    Queensland
    Posts
    5,234
    Location
    Hmmm.... you are more English than I thought.
    Remember To Do the Following....
    Use [Code].... [/Code] tags when posting code to the thread.
    Mark your thread as Solved if satisfied by using the Thread Tools options.
    If posting the same issue to another forum please show the link

Tags for this Thread

Posting Permissions

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