Results 1 to 19 of 19

Thread: To declare or not to declare

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #6
    Administrator VBAX Master georgiboy's Avatar
    Joined
    Mar 2008
    Location
    Kent, England
    Posts
    1,305
    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.
    Last edited by Aussiebear; 05-07-2025 at 12:49 PM.
    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

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
  •