Let other users know how useful this tip is by rating it below. Got a tip or code of your own you'd like to share? Submit it here!
If you're trying to use your VB 6.0 based programs in a Visual Basic .NET environment, you could wind up with some unexpected error messages. One reason is that there are some differences between how variables are scoped between Visual Basic 6.0 and Visual Basic .NET, and the difference may affect how code written to VB 6.0 works in a VS.NET/VB.NET environment.
The basic principles are pretty simple, but the implications can be far-reaching. Fortunately, there is an informative error message that occurs when the new block scoping rules are violated, and fixing such problems is also relatively straightforward, through various means.
To begin with, scoping refers to the portions of code or procedures in which variables are defined (and thus, where they will normally have associated values). In VB 6.0, a variable can be declared anywhere inside a procedure and has full scope inside the entire procedure no matter where it may be declared (Microsoft calls this "full procedure scope"). In VB.NET variables declared within code blocks may be referenced only inside that code block, where a code block is defined as any set of statements that end with an End, Loop, or Next statement (Microsoft calls this "block scope").
It's not that the variables do not exist or contain no values outside the code blocks within which they have scope; it's only that for VB.NET such variables may be referenced only inside the block in which they're defined.
The following code example is legal in VB 6.0, but generates an error in VB.NET:
Dim k As Long For k = 0 to 5 Dim counter As Long counter = counter + 1 Next k MsgBox(counter)
In fact VB.NET returns an error message that states "variable 'counter' has not been declared" and occurs because counter is declared in the For statement block (from the For through the Next statement) but is also referenced outside that block in the last line of code in the example.
There are an infinite number of workarounds possible, but two will work quite nicely:
- If a variable needs true procedure scope, it should be declared at the beginning of the procedure before any code blocks are defined.
- If a block scope variable must be referenced outside the block, its value can be assigned to a procedure scope variable inside the block.
Either way, this provides a way to access that value outside the scope of a block variable if that should be necessary. The error message makes it easy to tell what's gone wrong, and it should be easy to restructure code in one of the two ways recommended to get things working in VB.NET.
Ed Tittel is a principal at LANWrights, Inc. a wholly-owned subsidiary of iLearning.com, where he writes and teaches on a variety of subjects, including markup languages, development tools, and IT certifications. Contact Ed via e-mail at firstname.lastname@example.org.