Categorizing Data in Visual Basic

You work every day with many kinds of data, including text and numbers. Where you store information on your computer depends on what kind of information it is. If it's text, you probably store it in a Word document; if it's numerical values or mathematical formulas, you probably store it in a Microsoft Excel workbook or Microsoft Access database; and if it's graphics, you most likely store it in a PowerPoint presentation. By storing information in a file of an Office application, you're telling the recipient of that file what type of data it contains.

Variables and Constants

Visual Basic, like most other programming languages, uses a variable or constant to represent and temporarily store data that you use in your program. A variable, on the one hand, represents data that changes—its value varies within a program. A constant, on the other hand, represents data that stays the same throughout your program. The syntax for defining variables and constants has two parts: a name and a corresponding value. These two parts are joined by an equal sign. The name of the variable or constant is stated on the left side of the equal sign, and the value is stated on the right. In the section "Specifying Declaration Statements" later in this chapter, you'll learn how to use variables and constants in code.

Determining the Data Type

When you assign a value to a variable or constant, it's of a specific type. In Visual Basic, you can explicitly categorize your data, or information, type. For example, if you're working with text, the equivalent Visual Basic data type category is String. If you're working with whole numbers less than 32,767, the data type is Integer. The table below lists more details on other numerical data types, as well as listing the Boolean, String, and Object data types.

Data typeRange
Integer -32,768 to 32,767
Long (long integer) -2,147,483,648 to 2,147,483,647
Single (single-precision floating-point)-3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values
Double (double-precision floating-point)-1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values
Boolean True or False
Object (Any property or method in an object library that returns a reference to an object.)
String (fixed-length) 1 to approximately 65,400

NOTE
The preceding table isn't comprehensive; there are many other data types. For more information, in the Visual Basic Editor ask the Assistant for help using the words data type summary.

Examine User Input

  1. In the Code window, move the cursor beneath the End Sub line of the procedure you created earlier (MyNewProcedure) and create a new procedure by typing Sub InputType and pressing ENTER.
  2. Between the lines Sub InputType and End Sub, add the following line:
  3. sInput = InputBox("Enter text or a number.")
    

    InputBox is a function built into the Visual Basic programming language. This function displays a dialog box containing a text box in which you can type. If you enter text and click the OK button in the dialog box, the function returns the value you entered. In this case, the returned value is stored in the variable sInput.

  4. After the line containing the InputBox function, enter the following If…Then…Else statement:
  5. If IsNumeric(sInput) Then
        sType = "number"
    Else
        sType = "string"
    End If
    

    In this code segment, you use the built-in Visual Basic function IsNumeric to determine whether the value the user enters, which is stored in the variable sInput, is numeric. If it's numeric, Visual Basic stores the string value "number" in the variable sType. If the input value isn't numeric, Visual Basic stores the string value "string" in the variable sType.

  6. Finally, add the following message box statement as the last line (above End Sub) in the InputType procedure:
  7. MsgBox "The data you entered was a " & sType
    

  8. If Visual Basic displays a "Variable not defined" error, remove the Option Explicit statement at the top of the module. Place the cursor anywhere within the InputType procedure and press F5.
  9. You'll see a dialog box prompting you to enter text or a number. You can also enter a combination of text and numbers, although this combination is always considered a String data type in Visual Basic.

  10. Click OK to close the dialog box.

TIP
Visual Basic provides a convenient function called TypeName that performs a more robust version of the operation you performed in MyNewProcedure. TypeName returns a string indicating the type of information within a variable you specify. The MyNewProcedure only determines if the variable is a number or string. TypeName can determine if a variable is of any data type listed in the Data Type table. For more information, ask the Assistant for help using the word typename.

Specifying Declaration Statements

As you just learned, data is often of a specific type. For example, the whole number 12 is an Integer data type, and the text Hello there is a String data type. When you assign data to a variable, you'll want to tell Visual Basic what type of data you're using. To formally indicate this, you need to use a declaration statement.

Declaration statements for variables usually start with the keyword Dim, followed by the variable name and the type of data the variable should hold. The common syntax appears as:

Dim VariableName As DataType

The variable name must begin with a letter, can't be more than 255 characters long or contain any periods or mathematical operators, and must not be the name of a Visual Basic keyword. The data type can be any of the types discussed in the section of this chapter titled "Determining the Data Type" or any other types provided by Visual Basic.

You can specify more than one declaration at a time in a declaration statement, but you must specify the exact type for each variable. Visual Basic doesn't assume that the second variable is declared the same type as the first or any other declaration on the same line. By default, Visual Basic assigns the declaration without a specified type to the data type Variant. The following illustration shows variable declarations of several types.

Click to view at full size.

Declaration statements for constants start with the keyword Const, followed by the constant name, the type of data the constant should hold, and the value assigned to the constant. The common syntax appears as:

Const ConstantName As DataType = Value

The naming convention for a constant follows that of a variable name, as explained above. The data type can also be any of the types specified by Visual Basic. The value set to the constant must be a valid value within the range of the data type. The following simple procedure shows how to use the Dim and Const statements in your code:

Sub VariablesAndConstants()
    Dim iMyVariable As Integer
    Const iMyConstant As Integer = 10
    iMyVariable = 4
    MsgBox iMyVariable & ", " & iMyConstant
End Sub

Declaring variables and constants helps you reduce coding errors such as assigning an incorrect value or misspelling a name. As a good programming practice, you should place the keywords Option Explicit at the top of your code module. If you do, when Visual Basic runs your code it ensures that you explicitly declare and set a valid type of value to any variables and constants in your code. To have Visual Basic automatically add the keywords Option Explicit to every new code module you insert, in the Visual Basic Editor, click Options on the Tools menu, click the Editor tab, and then select the Require Variable Declaration check box.

Click to view at full size.

TIP
In programming you commonly prefix the name of each variable and constant with a letter that indicates the data type. This helps you and others reduce the time spent reading and debugging code because you can easily distinguish what type of data a variable or a constant should contain. For Visual Basic data types, a common syntax is to prefix each variable or constant as shown: s or str for String data type, i for Integer, bln or b for Boolean, lng or l for Long, sng or sg for Single, and vnt or v for Variant.

Declare the Scope of Variables and Constants

When you declare variables and constants, you also have to think about the scope in which they'll be available. Scope refers to the availability of a variable, constant, or procedure for use by another procedure. You can declare variables and constants at three levels: procedure-level, module-level, and public.

TIP
In addition to prefixing variables and constants with letters that indicate the data type, it's a good idea to include letters that indicate scope. This also helps you and others reduce the amount of time spent reading and debugging code because you can easily find where the variable or constant is declared. A common syntax is to prefix each variable or constant with m_ if it's module-level or g_ if it's public (the "g" stands for "global"). If the variable or constant is procedure-level, an additional prefix isn't used.