How to avoid clashes between variable names and built-in VBA function names

bluto32

New Member
By chance, I discovered that Excel doesn't warn you if you declare a variable with the same name as a built-in VBA function.
For example, the following compiles without errors:

Code:
Sub myProcedure
    Dim Day As String
    Day = "Monday"
End Sub

But now, the "Day" function cannot be used. I get an error ("Expected array") with this code:

Code:
Sub myProcedure
    Dim Day As String
    Day = "Monday"
    Debug.Print Day("23,5,1980")    [COLOR=#008000]'Offending line.[/COLOR]
End Sub

A Google search has revealed a workaround: use VBA.Day to invoke the function. But I would far rather that Excel warned me not to use Day as a variable name in the first place!

Is there a setting somewhere that prevents you from using built-in function names (such as Day, Date, Left, Right, etc.) as variable names?

Bluto
 

Tom Schreiner

Well-known Member
There is no RULE that says that you cannot use a VBA function name in your code. Unless there is ambiguity as in your second example, it's not really a problem because within the scope of your procedure the interpreter is able to discern your intention. In any case, when you compile, you will be told if there is a problem. In that case, change the name of your variable or fully qualify the second one with VBA.X. In other words, I wouldn't worry too much about it.
 

Peter_SSs

MrExcel MVP, Moderator
A common practice is to prefix your variables with something like these that identify the declaration type
Code:
Dim strDay As String
Dim blnStarted As Boolean
Dim lngLen As Long
This has two advantages
1. It should avoid the problem that you have encountered.
2. Especially if you have long code, when you read the variable name later in the code, you know what type it is declared as without having to refer back to your Dim statement
 

bluto32

New Member
Thank you both for your replies. I have toyed with the idea of using a naming convention of some sort, but was wondering first if there was a setting somewhere in Excel that would prevent these clashes. At least VBA sensibly prevents variable names from clashing with commands (such as Next) which would be disastrous!
Bluto
 

Fluff

MrExcel MVP, Moderator
Unfortunately there is nothing to prevent you from, or warn you about, using a keyword as a variable, or the name of a procedure.
 

Some videos you may like

This Week's Hot Topics

Top