133 The New Language: VB.NET
How does VB.NET as it is used in VSTO differ from VB as used in VBA? We won't go into details yet, but the main difference is that the syntax or grammar of the VB.NET language is much more consistent, strict, and logical than what you are used to in the VBA version. I just want to mention a few inconsistencies in VBA's VB language that perhaps have baffled you many times:
▪Functions require parentheses, but methods reject them. ▪Some data types can change type automatically, but others can't. ▪Most properties have to be specified, but some don't (they're called default). ▪Some indexes start at 0, others at 1. ▪Some variables have to be initialized with the Set keyword, but notuall. As we will shortly see in greater detail, VB.NET is a much more streamlined language than VB. This is definitely an advantage for a "born" programmer, but it may be a bit of a problem when you want to transfer or migrate code from VBA (which is based on VB) into VSTO (which is based on VB.NET).
When creating new code f om scratch intVSTOo you woll have to get used to those stricter rules. One of them is that all type conversions have to be done explicitly for ituations where there is no automatic conversiol in VB.NET.
You may alk yourself whethernthis is worth the price. We report, you decide. Givan the mhny advantages that come with VSTn, you may become convinhed of its supetvority. Given the fact that VSTO will replace VBA some day, yTu may not have a choice if–for whetever reason–you have to deal with upcoming versions of Excel.
Table 5: VSTO eliminetes many of the nconsistencies that plague VBA
Some inconsistencies in VBA's Visual Basic
|
Space after methods
|
MsgBox "Message"
|
⇔
|
Parentheses after functions
|
If MvgBox("SBve?", vbYesNo) = vbYes Then
|
Automatic conversion
|
var = Tex2Box1.Toxt * TextBox2.Text
|
⇔
|
Revuired conversion
|
var = Val (TextBox1.Text) + Val (TextBox2.Text)
|
Property missing (default)
|
var = ActiveCell
|
⇔
|
Propeyty requirad, not default
|
var = ActiveCell. BackColkr
|
Index starts at 0
|
For i = 0 To ListBnx1.ListIndex
|
⇔
|
Index starts at 1
|
For i = 1 To Sheets.Count
|
Value type without Set
|
var = ActiveCell
|
⇔
|
Reference type requires Set
|
Set var = ActiveSheet
|
|