Declaring variables in VBA

前端 未结 3 981
囚心锁ツ
囚心锁ツ 2020-12-11 11:45
Dim x, y as Date

What is the difference between these two code statements

Dim x as Date, y as Date

What is the pr

相关标签:
3条回答
  • 2020-12-11 12:07
    Dim x, y as Date
    

    As <Type> is required for each variable, so in the example above only y is a Date; x is a Variant (The default when no type is specified)

    Dim x as Date, y as Date
    

    Both variables are Dates as each has an As.

    0 讨论(0)
  • 2020-12-11 12:25

    For legibility I usually like to declare a variables contents on the same line I declare them in other languages. Is there any shortcuts to do this?

    For Constant expressions, yes:

    Const i as Integer = 6
    Const myName as String = "David Zemens"
    

    For dynamic variables, it's not possible without using the colon, i.e., Dim i as Integer: i = 6 but the colon is actually interpreted like a line-break, so there's no real advantage to doing so.

    And while assigning simple values known at design time can be done this way, if you look around you'll see this is simply not often-used in VBA programming. Instead, you typically will see ALL declarations at the top of module/procedure, followed by assignment statements for those variables which need an initial value. All other assignments happen during run-time at the point in the code where an assignment needs to be made or changed

    Dim i as Integer
    Dim x as Date
    Dim y as Date
    
    i = 1
    x = DateValue(Now())
    
    y = DateAdd("d", i, x)
    
    MsgBox y
    

    Compare the following:

    Dim i as Integer: i = 6
    

    Simple enough, right? But what about:

    Dim i as Integer: i = SomeFunction(arg1, arg2, obj.Property1)
    

    The above will work, but of course ONLY if the arguments for the function are assigned prior to this declaration, any object variables are instantiated, etc.

    What I'm saying is that while there are some cases where you could do this, in the vast majority of cases it's simply not practical to do so, and for consistency's sake, I would personally recommend against that sort of in-line declaration & assignment.

    0 讨论(0)
  • 2020-12-11 12:31
    Dim x, y as Date
    

    is the equivalent of:

    Dim x 
    Dim y as Date
    

    and that is the equivalent of:

    Dim x as Variant
    Dim y as Date
    

    When you omit the type for a variable, it assumes the Variant type

    Edit, per your question:

    Dim a! ' same as Dim a as Short
    Dim b@ ' same as Dim b as Currency
    Dim c# ' same as Dim c as Double
    Dim d$ ' same as Dim d as String
    Dim e% ' same as Dim e as Integer
    Dim f& ' same as Dim f as Long
    

    ref: http://bytes.com/topic/visual-basic/answers/643371-declaration-shortcuts

    0 讨论(0)
提交回复
热议问题