Be explicit

I’ve already mentioned that .NET doesn’t support VBA’s concept of a default property. If you are going to set the value of an object, you must use the Value property (or its equivalent).

Being explicit also applies to object references. It is much easier to program in .NET if you are using a specific object type, such as Worksheet, rather than the generic Object type. Using the specific object enables the Intellisense and Auto Complete features of .NET and helps detect inadvertent errors, such as incorrect variable assignments.

In many cases, Excel methods return generic object types that should be converted to the expected, more specific type. Use CType to perform this conversion, but be sure to check if the object can be converted before performing the conversion. For example, the following code checks if the passed-in argument Sh is a Worksheet before performing the conversion:

Private Sub ThisWorkbook_SheetActivate(ByVal Sh As Object) _
  Handles ThisWorkbook.SheetActivate
    If Sh.Type = Excel.XlSheetType.xlWorksheet Then _
      ActiveWorksheet = CType(Sh, Excel.Worksheet)
End Sub

Trying to convert an object to an incompatible type causes a runtime error.

In .NET, everything is an object. Even simple types like strings and integers are their own classes derived from .NET’s base object type. At first, this might seem cumbersome, but the consistency and logic of this approach pay huge dividends.

Get Programming Excel with VBA and .NET now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.