Variable declaration question

  • Thread starter Thread starter Nick via AccessMonster.com
  • Start date Start date
N

Nick via AccessMonster.com

Hello,

I was wondering if someone could help or point me in the right direction; I
searched but am not even sure of what search terms apply.

I had several string variables declared like this:

Dim strAlreadyAdded, strErrorMessage, strCannotAdd as String

I then tried to pass them to a Sub defined as:

Public Sub Validate_MDI(ByRef strCannotAdd As String, ByRef
strErrorMessage As String, ByRef strAlreadyAdded As String, ByRef Data_Error
As Boolean)

I compiled and received a message saying strErrorMessage (and later,
strAlreadyAdded) had a ByRef argument mismatch. I reorganized by declare
statement to only have one variable per line, and I had no problems.

My question is: When variables are declared in a line like in the first
statement, does VBA carry through the "as String" to all of them? I thought
it did at first, but not I'm not so sure... I use this type of declaration
structure when declaring recordsets, and have never had a problem. I want to
be sure I force declaration, I don't want to leave it up to Access to
"assume" what variable type I want, if that is what it's doing currently.

-Nick
 
Nick, this is an important question, and the answer is No.

The line:
Dim strAlreadyAdded, strErrorMessage, strCannotAdd as String
creates 2 variants (since no type was specified for the first 2), and one
string.

To get 3 strings, use:
Dim strAlreadyAdded As String, strErrorMessage As String, strCannotAdd
as String

Because this syntax does not match what some other programming languages do,
I suggest you use one line for each declaration.
 
Actually, while you've declared 3 variables, you've only declared one of
them (strCannotAdd) to be a string: the other two have been declared as
variants.

You can't "short circuit" declarations like that in VBA. To make all 3
strings, you need:

Dim strAlreadyAdded as String, strErrorMessage as String, strCannotAdd as
String

or, of course,

Dim strAlreadyAdded as String
Dim strErrorMessage as String
Dim strCannotAdd as String
 
Very interesting... thanks for both replies. It had never occured to me that
they would not "short circuit" into a string variable until I started looking
at the ByRef data coercion message, and wondered why VBA would coerce a
string into a string. This impacts quite a bit of my program; it is time to
search through and modify my subs.

And sorry for the numerous typos in my first post; it was a Monday morning
and I hadn't had my caffeine.

Again, thanks for the important advice.

-Nick
 
Back
Top