ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   Explicit declaration of variables (https://www.excelbanter.com/excel-programming/444294-re-explicit-declaration-variables.html)

Andrew Taylor

Explicit declaration of variables
 
On Monday, February 28, 2011 11:56:06 AM UTC, Slim Slender wrote:
Suppose a developer does not explicitly declare variables but just
makes up a variable and gives it a value when he needs it anywhere in
the code. He prefixes his variable names with "s" for string, "i" for
integer, "s" for single, etc. Is there some way I can examine this
code and determine that these variables are actually variant data type
and not the data type suggested by the prifix? Is there a way to
demonstrate or prove that this is not the best practice?


By far the most important reason for declaring variables (IMHO)
is to avoid problems caused by typos in variable names; for example:


myVariable = 1
'..
'... more code
'...
if myVaraible = 1 then ' note misspelt name
' ... do something
End if

Without Option Explicit this will run without
complaint but it will not work as expected and
could be very hard to debug. For that reason
alone I think Option Explicit should be mandatory.

You can use the Watch window to determine at
run time whether a variable is a Variant, but
I can't find a way to do so programatically:
The TypeName function gives the type as
determined by the latest assignment.

MsgBox TypeName(x) ' shows "Empty"
x = 1
MsgBox TypeName(x) ' shows "Integer"
x = "hello"
MsgBox TypeName(x) ' shows "String"



Andrew


All times are GMT +1. The time now is 01:11 PM.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
ExcelBanter.com