Reputation: 6984
Dim x, y as Date
What is the difference between these two code statements
Dim x as Date, y as Date
What is the pragmatic result of the difference and what other hidden declaration features am I missing?
Upvotes: 3
Views: 2516
Reputation: 1
Dim x, y as Date
'Is the same as:
Dim x as Variant
Dim y as Date
Now
Dim x as Date, y as Date
'Is the same as:
Dim x as Date
Dim y as Date
If you don't declare the data type for a VBA variable, VBA uses Variant (the default data type)
Upvotes: -1
Reputation: 53663
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.
Upvotes: 3
Reputation: 7778
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
Upvotes: 6
Reputation: 175956
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
.
Upvotes: 3