A function is similar to a subroutine, but a function returns a result. Subroutines perform a task and don’t report anything to the calling program; functions commonly carry out calculations and report the result. The statements making up a function are placed in a pair of function/ End function statements. Moreover, because a function reports a result, it must have a type, as in the following:
Function Next Day () As Date
Nest Day =date() + 1
End function
The next day () function returns tomorrow’s date by adding 1 day to the current date. Because it must report the result to the calling program, the Next Day() function has a type, as do variables, and the result is assigned to its name (which can’t be done with subroutines.)
The Exit function statement causes an immediate exit from a function procedure, as the Exit Sub statement does in the subroutine. Program execution continues with the statement following the statement that called the function.
Input Box Function
Display a prompt in a dialog box, waits for the user to input text or click a button and returns the content entered by the user.
Syntax
Input Box (prompt [title] [default] [xpos] [yops])
The arguments are described in the following table 1.3
Argument | Description |
prompt | Required string expression display as the message in the dialog |
Box.TitleOptional. String expression displayed in the title bar of the dialog
Box. If omitted, the application name is placed in the title bar.Default Optional. String expression displayed in the text box as the default
Response if no other input is provided. If omitted, the text box is
Displayed empty.XposOptional. Numeric expression that specifies, in twips, the horizontal distance of the left edge of the dialog box from the left edge of the
Screen. If omitted, the dialog box is horizontally centered.Yops Optional. Numeric expression that specifies, in twips, the vertical
distance of the upper edge of the dialog box from the top of the
screen. If is omitted, the dialog box is vertically positioned
approximately one-third of the way down the screen.
Table: Arguments of Input Box function
Example 1
Dim Name as String
‘specifying prompt alone
Name = inbox (“Your name please…”)
The above statement will display the input box as in figure 1.13
When the user enters his name and clicks OK, the Input Box return his name to the variable Name.
MsgBox Function
Displays a message in a dialog box, waits for the user to click a button and returns and integer indicating which button the user clicked.
Syntax
MsgBox (prompt [buttons][title])
The prompt and title arguments are same as in Input box function. The buttons argument is a numeric expression that is the sum of values specifying the number and type of buttons to display, the icon style to use, the identify of the default button, and the modality of the message box. If omitted, the default value for buttons is (). It settings are given in the following table 1.4
Vb OK only | 0 | Display OK button only |
Vb OK cancel | 1 | Display OK and cancel buttons |
Vb Abort Retry Ignore | 2 | Display Abort, retry and Ignore buttons. |
Vb Yes No Cancel | 3 | Display Yes, No and cancel buttons. |
Vb Yes No | 4 | Display Yes, and No buttons. |
Vb Retry Cancel | 5 | Display Retry and cancel buttons. |
Vb Critical | 16 | Display Critical Massage icon. |
Vb Question | 32 | Display warning Query icon. |
Vb exclamation | 48 | Display Warning Message icon. |
Vb Information | 64 | Display Information Message icon. |
Vb Default button 1 | 0 | First button is default |
Vb Default button 2 | 256 | Second button is default |
Vb Default button 3 | 512 | Third button is default |
Vb Default button 4 | 768 | Fourth button is default. |
Table: Values of the buttons argument.
Example 1
MsgBox “you mistyped everything!!! So try again”
This statement display a simple message box as in figure 1.15
Control Flow Statements
Programs are not monolithic sets of commands that carry out the same calculations every time they are executed. Instead, they adjust their behavior depending on the data supplied or based on the result of a test condition. Visual Basic provides three – control flow, or decision, structures to take a course of action depending on the outcome of test. They are
- If… Then
- If… Then…Else
- Select case
If … Then … End If
The if structure test the condition specified and, if it it’s true, executes the statement (s) that follow. The if structure can have a single line or multiple line syntax.
If condition Then Statement
In the above statement, Visual Basic evaluates the condition and, if it’s true, executes the statement that follows. If the condition is not True, it conditions with the statement following the If structure. Multiple statements can also supplied, provide they must be separated by colon as in the following:
If condition Then Statement1: Statement2: Statement3
Here is an example of single line in statement:
If Salary > 3000 Then DA percent =100
This statement can be broken into multiple lines, as it will be easier to read as follows:
If Salary > 3000 then
DA percent =100
End if
When a statement that is to be executed, are placed next to the if statement’s line, to mark the end of if block End If statement is used as in the above example.
If … Then … Else … End … If
A variation of the If … Then is the if … Then … Else Statement, which executes one block of statements if the condition is true and another if the condition is false .
Syntax
If condition Then
Statement block – 1
Else
Statement block – 2
End if
Visual Basic evaluates the condition. If it’s true, it executes the first block of statements and then jumps to the statement following the End If statement. If the condition is False, Visual Basic ignores the first block of statements and executes the block following the Else Keyword.
Example
If salary >5000 Then
DaPercent =100
Hra Percent = 80
Else
Dapercetn = 80
Hrapecent = 60
End if
Another variation of the If… Then … Else statement uses several conditions, with the Elseif keyword.
Syntax
If condition 1 Then
Statement block -1
Elseif condition2 Then
Statement block – 2
Elseif condition3 Then
Statement block – 3
Else
Statement block – 4
End if
A If statement can have any number of Else if clauses. The conditions are evaluates from the top, and in one of them is True, the corresponding block of statements is executed. The Else clause will be executed if none of the previous expressions is True.
Example
If score > 90 Then
Result = “Excellent”
Elseif Score >75 Then
Result = “Very Good”
Elseif Score > 50 Then
Result = “Good”
Else
Result = “Failed”
End If
This statement is easier to read, but not as efficient in terms of execution time because Visual Basic evaluates all conditions, even if the first one in True. This inefficiency is overcome with Select case statement.
Select Case
The select case structure compares the same expression to a different value. The advantage of the select case statement over multiple if. Then. Else statement is that it makes the code easer to read and maintain.
Syntax
Select case expression
Case Value 1
Statement block – 1
Case Value 2
Statement block – 2
—————- —————
———————————
Case Else
Statement block -3
End Select
Some case statements can be followed by multiple values, separated by commas or can have a range or a single condition as given in the example below.
Dim Number as Integer
Number = {Some integer value}
Select Case Number ‘Evaluate Number’
Case 1
Print “Number-1”
Case 2, 3,4,5,6 ‘Number between 2 and 6’
Print “Number – between 2 and 6”
Case 7 to 10 ‘Number between 7 and 10’
Print “Number –between 7 and 10”
Case Is <=20
Print “Number –between 11 and 20”
Case Else
Print “Number Not between 1 and 20”
End select
Loop statements
Loop statements allow executing one or more lines of code repetitively. Many task consists of trivial operations that must be repeated over and over again, can be done using loop statement. Visual Basic supports the following loop statements:
Do… Loop
The Do…Loop statement is used to execute a block of statements for an indefinite number of times. There are several variations of the Do… Loop statement, but each evaluates a Boolean Condition to determine whether a continue execution. As with if… then, the condition must be a value or expression that evaluates to False 9zero) or to True (nonzero).
The following Do … Loop executes the statements as long as the condition is True:
Do While Condition
Statement
Loop
When Visual Basic executes this Do Loop, it first tests condition. If condition is False 9zero0, it skips past all the statement. If it’s True (nonzero), Visual Basic executes the statements and then goes back to the Do while statement and tests the condition again.
Consequently, the loop can execute any number of times. As long as condition is nonzero or True. The statements never execute if condition is initially False.
Example
In this example the loop block is executed while the variable 1 is equal to 10
Dim I as Integer
I = 10
Do while I = 10
I= {some Expression} ‘Some expression may return 10 or other value.
Loop
When the condition I = 10 is tested, the result will be true as I holes the value 10. so the execution of the loop block will begin. If some expression returns 10, the loop block will be executed again. Otherwise the execution will jump on the next statement of the loop block.
Another variation of the Do… Loop statement executes the statements first and then tests condition after each execution. This variation guarantees at least one execution of statements:
Do
Statements
Loop while condition
For … Next
Do … loop is useful when a block of statements are to be executed for unknown number of times. But if a block of statements are to be executed for specific number of times the a For … Next loop is a better choice. Unlike a do loop, a for loop uses a variable called a another that increases or decrease in valued during each repetition of the loop.
Syntax
For counter = start To End [Step Increment]
Statements
Next [counter]
For Each … next
A for each … next loop is similar to a for … Next loop, but it repeats a group of statements for each element in a collection of objects or in an array instead of repeating the statements a specified number of times. This is especially helpful when the number of elements of a collection is not know.
Syntax
For Each element In group
Statement
Next element
Example
This example prints the contents of array Names.
Dim Age (10) as integer
Dim Item ‘Must be variant when used with arrays
———————–
———————–
For each item in Age ()
Print item
Next
With … Endwith
WITH … ENDWITH provides a convenient way to specify a number of properties for a single object. Note that you can also execute methods from within a WITH … ENDWITH structure, specifies multiple properties for an object.
Syntax
WITH object name
Statement
ENDWITH