In Part 1 we touched the basic’s, now we will move to the next step.
System Defined Functions: Now the second chapter, we will deal first with some of the system-defined functions in vb. What is this “function” ? Well a function is a special type of procedure that returns a value each time it is called. A function is generally used to perform a particular task/s repeatedly when needed. Visual basic provides several built-in functions as part of the programming language, such as MsgBox, Round and so on. We can also create our functions which does a user defined task. We can pass arguments to that function and return a value also based on the parameters. There are 4 types of functions in Visual Basic and they are as follows
- Conversion Functions
- String Functions
- Application Enhancement Functions
- Date Functions
Conversion Functions: As the name indicates these functions are used to convert one datatype variable to another datatype. The functions are as follows
|Asc||Returns a character code corresponding to the first letter of a given string.|
|Chr||Return the character associated with the specified character code.|
|Cbool||Converts an expression to boolean.|
|Cbyte||Converts an expression to byte|
|Ccur||Converts an expression to currency|
|Cdate||Converts an expression to date|
|CDbl||Converts an expression to double|
|Cint||Converts an expression to Integer|
|Clang||Converts an expression to long|
|CSng||Converts an expression to single|
|CStr||Converts an expression to string|
|Cvar||Converts an expression to variant|
|Str||Returns the string representation of a number|
|Val||Returns number equivalent of a string|
Function_name is the conversion function to be used
Expression/string/number is the input given to the conversion function
String Functions: A String variable can be of fixed length or variable length. You know that the default size of the string depends on the text assigned to it. Visual basic has more than 45 functions for string manipulation but the most commonly used examples are as follows
Trimming a String: The following three functions are used to return a copy of a string without spaces
sVar1=" Hello " 'Assume this is the string you have sLTrimVar = Ltrim(sVar1) 'returns "Hello " sLTrimVar = RTrim(sVar1) 'returns " Hello " sLTrimVar = Trim(sVar1) 'returns "Hello "
Comparing Strings: Strings can be compared for their value by using the StrComp function and the Like operator.
StrComp (String1, String2, [compare type]) 'String1 is any valid string 'String2 is any valid string
Compare type is an optional argument that specifies the type of comparison. You can compare the textual value or do a binary comparison on the string. In compare we can give three types of compares which are
- VbBinaryCompare (Does a byte by byte comparison, is case sensitive)
- VbDatabaeCompare (Compare information inside database)
- VbTextCompare (Does case insensitive compare)
Dim sVar1 as String, sVar2 as String SVar1=”NETHS” SVar2=”neths” MsgBox StrComp(sVar1, sVar2, VbBinaryCompare) ‘Returns –1 MsgBox StrComp(sVar1, sVar2, VbTextCompare) ‘Returns 0
Reversing Strings: Strings can be reversed using the function StrReverse function. This function returns the character of the specified string in reverse order
Dim sResult As String sResult = StrReverse("Hello Nethaji") Msgbox sResult 'displays ijahteN olleH
Search Functions: The InStr function is used to return the position of the occurrence of a string within another string.
InStr ([start position], String1, String2, [compare-type])
Start position is a numeric expression indicating the starting position for the search. If this is not specified it search starts from the first character. The start position and compare-type are optional. The compare types are similar to that of the StrComp Function.
Dim sVar1 As String, sVar2 As String sVar1 = "Hello Nethaji, It's a nice day" sVar2 = "nethaji" MsgBox InStr(1, sVar1, sVar2, VbBinaryCompare) 'Returns 0 MsgBox InStr(1, sVar1, sVar2, VbTextCompare) 'Returns 7
String Extraction: This function allows you to replace the characters at any arbitrary location in a string.
Mid (sSourceString, StartPosition, Length)
Dim sVar1 As String sVar1 = "Nethaji is Coding" MsgBox Mid(sVar1, 1, 7) 'Displays Nethaji
Visual Basic offers 45 string functions, some of which have been explained. The rest I leave you to find and explore.
Date Functions: The calculation and modifications of dates can be done with certain date functions and modifications to the time part of a Date variable. VB offers 25 date functions. Some of the commonly used functions are listed below.
|Date||Date||Returns Current Date||Msgbox Date|
|Now||Now||Returns current date and time.||Msgbox Now|
|Day||Day(Date)||Returns a numeric representation of current day.||Msgbox Day(Date)|
|Month||Month(Date)||Returns a number between 1 and 12 representing a month.||MsgBox Month(Date)|
|DateAdd||Date(interval,number,date)||Returns a variant containing a date to which a specified time interval has been added. The interval can be
|MsgBox DateAdd(“d”, 1, Date)|
|DateDiff||DateDiff(interval,date1,date2)||Returns the number of time intervals between two dates.||MsgBox DateDiff(“d”, “13-June-99”, “14-June-99”)|
Note: The parameter “d” indicates interval in days. In the same lines we have the following list
- “n” returns in minutes
- “h” returns in Hours
- “m” returns in months
- “y” returns in years
- “s” returns in seconds
Application Enhancement Functions: In windows-based applications, dialog boxes are used to prompt a user for appropriate date or to display information for users. Visual basic allows you to create dialog boxes with predefined functionality. Msgbox and InputBox are the functions for creating such dialog boxes. These dialog boxes must be closed before you continue to work on the rest of the application. These are also called modal dialog boxes.
Msgbox Function: A modal Dialogbox with a predefined set of buttons (from which you can choose). You can click this link for a detailed study on the constants.
Msgbox (“Hi Nethaji”,vbOkOnly,”Nethaji’s First Msgbox”)
InputBox Function: The InputBox function displays a prompt in a dialog box and waits for the user to enter text. The function returns the text that has been entered by the user.
InputBox (prompt, [title], [default], [xpos], [ypos])
MsgBox InputBox("Your Age", "Nethaji's Age", "67")
Control Structures: Control structures enable you to execute a certain set of statements based on a condition. The condition should be specified at the design time. At runtime, the condition is evaluated, and depending on the result of the condition, the block of code following the condition is executed. These structures are also known as decision structures. These include the If….. Then…Else and the Select Case.
If ………. Then ………. Else Statement
You can use the if statement where there is a need to execute a statement of a set of statements based on a condition. For instance here’s a sample if statement that checks whether the value of the variable is greater than 10.
If iVar1 > 10 then Msgbox “iVar1 greater than 10” Else Msgbox “iVar1 lesser than 10” End if
One more thing is that you can nested Ifs that is an if Within an If. We also have something called Else Ifs, Here’s an example of it.
If iVar1=1 then Msgbox “iVar1 is 1” Elseif iVar1=2 then Msgbox “iVar1 is 2” Elseif iVar1=3 then Msgbox “iVar1 is 3” Else Msgbox “iVar greater than 3” End if
Select Case Another alternative to the If. Else statement is the Select Case statement. Here’s an example to illustrate my point
Select Case iVar1 Case 1 Msgbox “iVar is 1” Case 2 Msgbox “iVar1 is 2” Case 3 Msgbox “iVar1 is 3” Case Else Msgbox “iVar greater than 3” End Select
Loop Structures: Looping structures are used when a group of statements is to be executed repeatedly, based on a condition. There are 4 types of loop structures in VB, and they are as follows
- Do. Loop
- While.. Wend
- For.. Next
- For Each.. Next
Do.. Loop This loop construct is used to repeat the execution of a block of statements based on a condition. This loop construct evaluates a condition to determine whether or not to continue the execution. There are 4 ways a Do. Loop can be written.
1. Do While <condition>
Tests the <condition> first and, if true, executes the <statements> loops based on condition.
Executes the <statements> first and then tests the <condition> Loops at least once, then tests the condition
3. Do Until
Tests the <condition> first and, if False, executes the <statement> Loops till the condition if False
Executes the <statements> and then tests the <condition> Loops at least once, then tests the condition Executes till the condition is False.
Dim iCnt As Integer Do While iCnt <= 10 MsgBox iCnt iCnt = iCnt + 1 Loop ‘This loop executes till the value of iCnt reaches 10
While. Wend Loop The While. Wend loop structure allows you to perform a series of steps based on a condition.
Dim iCnt As Integer While iCnt <= 10 MsgBox I iCnt = iCnt + 1 Wend 'This loop executes till the value of iCnt reaches 10
For.. Next Loop: The For .. Next loop uses a counter that increases or decreases the value of a variable each time the loop is executed.
For <Counter>=<Start> To <End> [Step Value]
Some examples for “for” loops are
'First Dim iCnt As Integer For iCnt = 0 To 10 MsgBox iCnt Next iCnt 'The loop executes till iCnt reaches 10. It is not necessary to give "Next iCnt", as the loop automatically increments the value. 'Second Dim iCnt As Integer For iCnt = 0 To 10 Step 2 MsgBox iCnt Next 'The end result will be the same but if you notice you will be displayed on even number that is iCnt is always incremented by 2. That’s the use of Step keyword.
For Each.. Next Loop
The For Each.. Next loop is used to perform an operation on each element of an array or collection.
Dim sCollection As New Collection Dim sCurItem As Variant sCollection.Add ("ProgrammingFundas.com") sCollection.Add ("NonStopSense.Net") sCollection.Add ("VBCity") For Each sCurItem In sCollection MsgBox sCurItem Next
With.. End With You can write a number of code statements that act on the same object. To make this type of code more efficient and easier to read, we can use the With and End With statement. The statement allows you to set multiple properties and call multiple methods quickly and easily. Since the object is referenced only once, the code executes faster.
With TxtName .Font.Italic = True .Font.Size =24 .Text = “Hello Nethaji” End With