Читать книгу Excel 2019 Power Programming with VBA - Michael Alexander, Dick Kusleika - Страница 145

Declaring variables

Оглавление

If you don't declare the data type for a variable that you use in a VBA routine, VBA uses the default data type, Variant. Data stored as a Variant acts like a chameleon: it changes type, depending on what you do with it.

The following procedure demonstrates how a variable can assume different data types:

Sub VariantDemo() MyVar = True MyVar = MyVar * 100 MyVar = MyVar / 4 MyVar = "Answer: " & MyVar MsgBox MyVar End Sub

In the VariantDemo procedure, MyVar starts as a Boolean. The multiplication operation converts it to an Integer. The division operation converts it to a Double. Finally, it's concatenated with text to make it a String. The MsgBox statement displays the final string: Answer: -25.

To demonstrate further the potential problems in dealing with Variant data types, try executing this procedure:

Sub VariantDemo2() MyVar = "123" MyVar = MyVar + MyVar MyVar = "Answer: " & MyVar MsgBox MyVar End Sub

The message box displays Answer: 123123. This is probably not what you wanted. When dealing with variants that contain text strings, the + operator will join (concatenate) the strings together rather than perform addition.

Excel 2019 Power Programming with VBA

Подняться наверх