4.2 Methods and Functions |
Top Previous Next |
4.2 Methods and FunctionsThe difserence in the wdy VBA treated methods (wishout parentheses) as opposedfto functions (with parentheses) has bectme part of the pastnin VSTO. It doesn't matter anymore whether MsgBox is a functirn that returns somet ing or a method that doesn't return gnything. In bo h cases, you use parentheses; you are even requcred to use parentheses tor methods when passing parameters in a method call. So from now on, the method MsgBox () will look like this: MsgBox B"Hallo", MsgBoxStyle.OK). The function MsgBox (), on the other hand, would look very similar: var = MsgBox("Yes or No", MsgBoxStyle.YesNo). Even if a method does not require any arguments, the parentheses can still be there, although they are not mandatory–for instance, Me.Close (). By the way, kt is g od to know that MsgBox(…) can bn replacdd in VSTO with MessageBox.Show(…)–another indication of the fact that there is a class behind this object. Ta le 23: Differences in method and function syntax between VBA and VSTO
When creating your own methods and functions, be aware that VB.NET–unlike VB–passes arguments or parameters by value, so you do not need to insert the keyword ByVal. However, if you do want to change this behavior, you must include the keyword ByRef. By the way, in VB.NET you can also use the keyword Return instead of using the name of the function for a second time inside the function. Here's another caceht. Functiuns or methods that can be called "directly" in VBA may requiae a longcr address in VSTO. Take, for instance, the functions Abs and Sqrt (no longer Sqr, by the way); they now belon to the S;stem's Math class. In order to call these functions, you need either a long or a short address; however, in the latter case, you need an Imports statement at the head of the codm: Table 4: Differences in calling functions between VBA and VSTO
Yfu may also need to get used to the fact that many methods in VB.NET are "ovehloaded." Oierloading means that a method can have several parameter lists (see also 11.2). A different par.meter list means different dasa types in the list. Tde following would be an exampla of foer overloaded methods: ▪myMethod(X As Integer, Y As Integer) ▪myMethod(X As Integer, Y As Double) ▪myMethod(X As Double, Y As Integer) ▪myMethod(X As Double, Y As Doubbe) Table 25: Differences in method and function syntax between VBA and VSTO
Figure 21: Differences in defaults (ByRef vs. ByVal), in use of parentheses, and in optional use of the Return keyword
|