Docsity

VB Programming Fundamentals: Variables, Constants, and Data Types in VB - Prof. Jingxin Wa, Study Guides, Projects, Research of Forestry

Toggle sidebar
bg1
FOR 240 Introduction to Computing in Natural Resources
20. VB Programming Fundamentals – Variables and Procedures
20.1 Variables and Constants
VB, like other programming languages, uses variables for storing values.
Variables have a name and a data type. Array can be used to store indexed collections of
related variables.
Declaring Variables
You declare a variable with the Dim statement, supplying a name for the variable:
Dim variablename [as data type]
A variable name:
- Must begin with a letter.
- Can’t contain an embedded period or embedded type-declaration character.
- Must not exceed 255 characters.
- Must be unique within the same scope, which is the range from which the
variable can be referenced.
The Scope of Variables
The scope is the lifetime of a variable. Depending on how it is declared, a
variable is scoped as either a procedure-level (local) or module-level variable (Table 1).
Table 1. Scope of variables.
Scope Private Public
Procedure-
level Variables are private to the procedure
in which they appear. Not applicable. You cannot
declare public variables within a
procedure.
Module-level Variables are private to the module in
which they appear. Variables are available to all
modules.
Implicit vs. Explicit Declaration
You don’t have to declare a variable before using it, which refers to as Implicit
declaration. While it is convenient, it can lead to subtle errors in your code if you
misspelled a variable name.
You can avoid the problem of misnaming variables by using Explicit declaration.
To explicitly declare variables,
- Simply place this statement ā€œOption Explicitā€ in the Declarations section of a
class, form or standard module, or
VB Variables and Procedures, Prepared by Dr. Jingxin Wang 1
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download VB Programming Fundamentals: Variables, Constants, and Data Types in VB - Prof. Jingxin Wa and more Study Guides, Projects, Research Forestry in PDF only on Docsity!

20. VB Programming Fundamentals – Variables and Procedures

20.1 Variables and Constants

VB, like other programming languages, uses variables for storing values. Variables have a name and a data type. Array can be used to store indexed collections of related variables.

Declaring Variables

You declare a variable with the Dim statement, supplying a name for the variable:

Dim variablename [as data type]

A variable name:

  • Must begin with a letter.
  • Can’t contain an embedded period or embedded type-declaration character.
  • Must not exceed 255 characters.
  • Must be unique within the same scope, which is the range from which the variable can be referenced.

The Scope of Variables

The scope is the lifetime of a variable. Depending on how it is declared, a variable is scoped as either a procedure-level (local) or module-level variable (Table 1).

Table 1. Scope of variables. Scope Private Public Procedure- level

Variables are private to the procedure in which they appear.

Not applicable. You cannot declare public variables within a procedure. Module-level Variables are private to the module in which they appear.

Variables are available to all modules.

Implicit vs. Explicit Declaration

You don’t have to declare a variable before using it, which refers to as Implicit declaration. While it is convenient, it can lead to subtle errors in your code if you misspelled a variable name. You can avoid the problem of misnaming variables by using Explicit declaration. To explicitly declare variables,

  • Simply place this statement ā€œOption Explicitā€ in the Declarations section of a class, form or standard module, or
  • From the Tools menu, choose Options…, click the Editor tab and check the Require Variable Declaration.

Private vs. Public

Static vs. Dim

Constants also store values, but as the name implies, those values remain constant through the execution of an application. Using constants can make your code more readable by providing meaningful names instead of numbers.

[Public|Private] Const constantname[As Type] = expression

Public Const conPaxPlanets As Integer = 9

20.2 Data Types

Data types control the internal storage of data in VB. By default, VB uses the Variant data type. There are a number of other available data types in Visual Basic.

Numeric data types

  • Integer
  • Single
  • Double
  • Currency

String data type Private S As String ā€˜Variable-length string Private S As String * 10 ā€˜Fixed-length string

If you assign a string of fewer than 10 characters, S is padded with enough trailing spaces to total 10 characters. If you assign a string that too long for the fixed-length string, VB simply truncates the characters.

Boolean data type Dim blFlag As Boolean

Object data type Dim objDB As Object Set objDB = OpenDatabase(ā€œC:\LogInventory.mdbā€)

  • Sub procedures do not return a value.
  • Function procedures return a value.
  • Property procedures can return and assign values, and set references to objects.

Sub Procedures

A Sub procedure is a block of code that is extended in response to an event. There are two types of Sub procedures – General and Event procedures. The syntax for a Sub procedure is:

[Private][Public][Static]Sub procedurename (args)

statements

End Sub

Event Procedures

When an object in Visual Basic recognizes that an event has occurred, it automatically invokes the event procedure using the name corresponding to the event. Because the name establishes an association between the object and the code, event procedures are said to be attached to forms and controls. An event procedure for a control combines the control’s name, and underscore ā€œ_ā€ and the event name. For example, if you are using a command button to invoke actions by clicking the button, this event procedure will be:

Private Sub command1_click()

…

End Sub

An event procedure for a form combines form name, underscore, and event. For example, if you are using form1, you can have the following event procedures for this form:

Private Sub Form1_click() … End Sub

Private Sub Form1_Load() … End Sub

General Procedures

A general procedure tells the application how to perform a specific task. Once a general procedure is defined, it must be specifically invoked by the application. By

contrast, an event procedure remains idle until called upon to respond to events caused by the user or triggered by the system. Why use general procedures?

  • Several different event procedures might need the same actions performed.
  • This will eliminate the need to duplicate the code.
  • This is the way of modular programming.

Function Procedures

VB includes built-in functions, like Sqr, Cos or Sin. In addition, we can build our own functions. The syntax for a function procedure is:

[Private][Public][Static]Function functionname (args) [As type]

statements

End Function

Like a Sub procedure, a function is a separate procedure and can perform a series of statements. However, there are two basic differences between a Sub procedure and a function:

  • a function can return a value. While calling a function, we need to use the expression such as returnvalue = functionname(args).
  • A function have data type.

Example

Here is an example to show you how to use procedures. Suppose we would like to calculate the basal area of a tree and display it in a list box.

(1) Start a new VB project. (2) Create the interface

We need to add the following controls on form1 (Figure 1):

  • two labels
  • a text box
  • a list box
  • two command buttons

ā€˜Event procedure of clicking command Private Sub Command2_Click()

End

End Sub

You should notice that two VB built-in functions we used in the program: CSng – convert single CStr – convert to string

(4) Run the Project

  • Enter a dbh in the text box
  • Click ā€œCal BAā€ button
  • Repeat the above procedures

Passing by value vs. passing by reference

Only a copy of a variable is passed when an argument is passed by value. If the procedure changes the value, the change affects only the copy and not the variable itself. Use the ByVal keyword to indicate an argument passed by value.

Passing arguments by reference gives the procedure access to the actual variable content in its memory address location. As a result, the variable’s value can be changed permanently. Passing by reference is the default in VB.

20.5 Control Structures

Control structures allow you to control the flow of your program’s execution. In this lecture, we are going to learn Decision Structures and Loop Structures.

Decision Structures

VB procedures can test conditions and then, depending on the results of the test, perform different operations. The decision structures that VB supports include:

(1) If … Then

If condition Then statement

If condition Then

Statements

End If

(2) If … Then … Else

If condition1 Then

Statement block 1

ElseIf condition2 Then

Statement block 2

…

Else

Statement block n

End If

(3) Select Case

Select Case testexpression Case expressionlist Statementblock Case expressionlist Statementblock

…

Case Else Statementblockn End Select

Loop Structure

Loop structures allow you to execute one or more lines of code repetitively. The loop structures that VB supports include:

(1) While … Wend

While conditions

Statements

Wend

(2) For … Next

For counter = start To end [Step increment]