Beginner’s Guide to Visual Basic 6 – Part 2

March 24th, 2009 by vikramjb

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

  1. Conversion Functions
  2. String Functions
  3. Application Enhancement Functions
  4. 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

Function Description
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

Syntax:
Function_name <expression/string/number>

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

  1. Trim
  2. StrReverse
  3. StrComp
  4. InStr
  5. Mid
  6. Lcase

Trimming a String: The following three functions are used to return a copy of a string without spaces

  1. LTrim
  2. RTrim
  3. Trim

Example:

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.

Syntax:

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

  1. VbBinaryCompare (Does a byte by byte comparison, is case sensitive)
  2. VbDatabaeCompare (Compare information inside database)
  3. VbTextCompare (Does case insensitive compare)

Example:

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

Syntax:

StrReverse (String1)

Example:

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.

Syntax:
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.

Example:

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.

Syntax:
Mid (sSourceString, StartPosition, Length)

Example:

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.

Function Syntax Description Example
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
y,q,m,w,d,h,s
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.

Syntax:
Msgbox (prompt,[buttons],[title],[helpfile-context])

Example:

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.

Syntax:
InputBox (prompt, [title], [default], [xpos], [ypos])

Example:

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 &gt; 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

Example:

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

  1. Do. Loop
  2. While.. Wend
  3. For.. Next
  4. 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>
<Statements>
Loop

Tests the <condition> first and, if true, executes the <statements> loops based on condition.

2. Do
<Statements>
Loop While

Executes the <statements> first and then tests the <condition> Loops at least once, then tests the condition

3. Do Until
<Statements>
Loop

Tests the <condition> first and, if False, executes the <statement> Loops till the condition if False

4. Do
<Statements>
Loop Until

Executes the <statements> and then tests the <condition> Loops at least once, then tests the condition Executes till the condition is False.

Example:

Dim iCnt As Integer
Do While iCnt &lt;= 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.

Syntax:

While <condition>
<Statements>
Wend

Example:

Dim iCnt As Integer
While iCnt &lt;= 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.
Syntax:

For <Counter>=<Start> To <End> [Step Value]
[Statements]
Next <Counter>

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.

Example:

With TxtName
.Font.Italic = True
.Font.Size =24
.Text = “Hello Nethaji”
End With
VN:F [1.8.1_1037]
Rating: 0.0/10 (0 votes cast)
VN:F [1.8.1_1037]
Rating: 0 (from 0 votes)
Share and Enjoy:
  • Digg
  • Google Bookmarks
  • del.icio.us
  • Furl
  • LinkedIn
  • Live
  • Reddit
  • StumbleUpon
  • TwitThis
  • Yahoo! Buzz
  • YahooMyWeb

Leave a Comment

Beginners Guide to Visual Basic 6 – Part 1

March 21st, 2009 by vikramjb

I’ve seen couple of posts in the site where people have like asked the basic questions about VB. For instance, is there a need to declare a variable and what is the use of a module and so on. So this is tutorial is first of the series that I am writing. Now I will go for some bookish definition of VB.

General Information on Visual Basic 6.0
Visual Basic 6.0 is RAD tool. RAD means Rapid Application Development Tool. It is very easy to create a Data-Entry Form using VB. If it takes a 6 months for you to create a C++ application, it will take only 6 minutes for you to do it in VB. VB 6.0 has many powerful features that are required in today’s programming environment. Some of them are as follows

  1. The visual forms and controls like listbox and radio buttons that you use on the form help you to interact with the application in order to find out the flow of the program.
  2. The forms and objects perform a specified action when an event occurs. This is known as event-drive programming.
  3. Visual Basic includes many wizards that can automate tasks or even automate coding. The tools provided by VB help you reduce development time. It is faster to create applications using the tools available.

A visual basic project is made up of forms, objects, and code modules that the application needs. Visual basic project file have the extension *.vbp, Standard Modules in Visual Basic have the extension *.bas and Class Modules have the extension *.cls. Now I will get into the programming part of Visual Basic where we will create some small applications get to do some processing with Visual Basic. I am assuming you have some familiarity with the Visual Basic IDE.

Data Types in Visual Basic
Every application needs to use data to generate the required output. The application may be built to perform simple tasks like addition or for complex database management such as airline reservations or storing bank transactions. The Data-Types provided by Visual Basic is known as. Some of the fundamental data types provided by Visual Basic are as follows

  1. Byte
  2. Boolean
  3. Integer
  4. Long (long integer)
  5. Single (single-precision floating-point)
  6. Double (double-precision floating-point)
  7. Currency
  8. Date
  9. Object
  10. String (variable length)
  11. String (Fixed Length)
  12. Variant (with numbers)
  13. Variant (with characters)
  14. OLE_COLOR

Those are the data types used in VB. I will not be giving a detailed description as I feel I cannot do a good enough job on that. In any case we will be using mostly all the data types displayed, except the last one OLE_COLOR. Why, because I don’t know what heck it is and neither have I used it. Now we will come to

Variables.

Variables are used to store data. It can be thought as a container in which data is stored. A variable essentially has two parts, a name, by which it is referred to and, a value. This value depends on the data type of the variable. One can declare a Variable using the Dim Statement.

Syntax:

Dim VarName As DataType

Here,
Var Name is the name of the variable and Type is Data Type of the variable.

Example:

Dim sVar1 as String

One can declare more than one variable in a single statement, for instance

Dim sVar1 as String, iVar2 as Integer

One need not specify the Data Type of the variable that one is declaring. In such a case, the variable is allotted the Variant data type and initialized to Empty. For instance

Dim varAnyVar
 
VarAnyVar = “Hello Nethaji” 'Now varAnyVar will store a string.
VarAnyVar = 10 'Now varAnyVar will store an integer.

The Variant data type offers benefits in terms of flexibility because you can assign any type of data to such a variable. However, it is a good programming practice to explicitly declare the type of the variable in order to avoid confusion and loss of data during conversions.

The String Declaration:

String variables can be declared of two types:

  • * Variable Length: A string variable is by default of variable length. This means that the size of the variable depends on the value that is assigned to it. For instance, if we assign the string “Hello” to a variable, the size will be 5 bytes. Then, if we assign “Hello Nethaji” the size will change to 13 bytes.Example:
          Dim sVar1 as String 'can store any number of characters
  • * Fixed Length: When we need to store a value of fixed length then we use Fixed Length string variables.Example:
          Dim sVarFixed as String * 100 'can store only 100 characters

Type Declaration Characters:
There is an alternative way of declaring a variable. You can declare a variable and specify the type of the variable by using type declaration character. A type declaration is a symbol that specifies the data type of the variable. In this case we do not have the As clause.

Dim iLocalVar% 'this declares iLocalVar as of Integer Type

A list of Type Declarations

  1. % denotes Integer
  2. $ denotes String
  3. @ denotes Currency
  4. & denotes Long
  5. # denotes Double
  6. ! denotes Single

In visual basic, certain rules and Naming Conventions have to be followed while specifying a name for a variable. I am not going delve into it, as you will already know what it is all about. But it is important that you name your variables appropriately and get used that because that’s the way professional program. If you name your variable appropriately then it will easier for you to identify the variable when maintaining them. As said earlier, one need not declare a variable as the default data type is taken as Variant and VB at runtime determines by checking the value. This concept is called implicit declaration. There’s nothing wrong in this method, but it is strongly recommended NOT to do this. When doing an implicit declaration there are possibilities that you might lose data. For instance, take this example.

intPrice = "3423"
intPrice = intPrice - (intPrice * 0.1)
Msgbox intPrice
 
'The output of this 3080.7, while if we declare the variable
 
Dim intPrice As Integer
 
intPrice = "3423"
intPrice = intPrice - (intPrice * 0.1)
Msgbox intPrice
 
'The output of this is 3081

One can clearly see the small data loss that has occurred when the runtime conversion was done. This might not be a serious threat for small scale application, but large scale applications need more protection from these kind of mistakes. Thus in order to ensure accuracy one needs to use Option Explicit in their projects. This can be enable by default. All you have to do is, Open Visual Basic Goto Tools and select Options. Enable the second check box which has the Text Require Variable Declaration.Now close visual basic IDE and open it again. Select a New project, you will notice that when you goto the code window, a line would’ve been added Option Explicit. This one line ensures that all variables are declared. Now to a particularly important part of Variable Declaration.

Scope of a Variable:

The scope of a variable determines the sections of an application in which the variable can be used. Visual basic offers four different types of a scope for a variable.

  1. Private: These variables are declared within a procedure and are local to the procedure.
  2. Module-level: These variables are declared using the keyword, Private, in a module and can be used by all the procedures in that module but not by procedures in other modules.
  3. Public: These variables are declared using the keyword, Public, and can be used by all the procedures in all the modules of a project.

Scope of a variable in forms and modules:

Forms

  1. When a variable is declared public here, it is accessible anywhere in the project. But the catch is that you have precede the forms name when accessing the variable (i.e.) FormName.Variable
  2. When a variable is declared private then its accessible only inside the form and not outside. You can declare a variable private by
    Dim iCnt as Integer (or) Private iCnt as Integer

Modules

  1. The first point similar to a module, except we don’t have to specify the module name
  2. Second point in forms is similar for modules

Class Modules

  1. Here if you declare a variable public, you will not be able to call it, unless and until you instanstiate the class. (E.g)
    Dim iClass As New Class1.
  2. Well if you declare private then it stays within the class module.

Scope Examples:

Private Sub SomeSub ()
    Dim iLocal As Integer
    iLocal =10
End Sub

In the above procedure’s case, the variable iLocal can be accessed only inside the procedure SomeSub ().

Dim iPublic as Integer

If this variable declared above all the coding and just below the Option Explicit, then it is said to have a global access. It can be accessed anywhere in the form. One important thing to note is that you cannot use scope qualifiers, such as Public or Private within a procedure. You need to use the Dim keyword within a procedure

Variables having the same name:

One can define more than one variable with the same name provide the scope of the variables is different. Therefore, the following cases are possible

  1. You can define variables with the same name in a module in which the scope of each variable is local.
  2. If you can declare a variable with the same name at the module level as well as within a procedure, the module-level variable has higher scope than that of the local variable. The module-level variable is said to have a higher level local scope and the procedure-level variable has a lower level local scope. In cases where you have defined a variable with the same name but with different scopes, the variable with the lower level scope is accessed when the variable name is referenced. This is known as shadowing.

For Instance:

'In the General Declaration Section if we Have
Option Explicit
Public iVar1 as Integer
 
'Then in a procedure if we have
Private Sub prcShadow ()
    Dim iVar1 as Integer
    IVar1=10 'local variable is being set value of 10 (shadowing)
    FormName.iVar1 = 100 'global variable is being set the value of 100.
End Sub

Static Keyword:
The Variables that are local to a procedure are destroyed once all the statements in the procedure are executed. However, in several cases, you might need to preserve the value of a variable after the procedure has been executed. This is especially useful if one needs to know the number of time a procedure has been called.

For Instance:

'Declare a static variable in a procedure
Private Sub prcStaticCheck()
    Static iCounter as Integer
    iCounter = iCounter + 1
    Msgbox "The Value of Counter is " &amp; iCounter
End Sub
 
'Then in the same form load's event
Private Sub Form_Load ()
Call prcStaticCheck () 'It will display 1
Call prcStaticCheck () 'It will display 2
Call prcStaticCheck () 'It will display 3
Call prcStaticCheck () 'It will display 4
End Sub

As you can see the value is retained in the variable if we declare the variable as static in declaration part. If a procedure is declared static then all the variables within the procedure retain the value. Okay with this I am ending my first part. Hopefully you should’ve understood most of the stuff that I have mentioned in this part. If you think i’ve missed something something i’ve typed something wrong, please do correct me.

VN:F [1.8.1_1037]
Rating: 0.0/10 (0 votes cast)
VN:F [1.8.1_1037]
Rating: 0 (from 0 votes)
Share and Enjoy:
  • Digg
  • Google Bookmarks
  • del.icio.us
  • Furl
  • LinkedIn
  • Live
  • Reddit
  • StumbleUpon
  • TwitThis
  • Yahoo! Buzz
  • YahooMyWeb

Comments (1)

Automatic Time Tracking an Overview

February 20th, 2009 by vikramjb

A lot of times, i have felt I have worked more than my body can handle but when I took tool of the tasks, it seems most of them were not completed or was in a very bad state. I was not sure where i was going wrong, I had a fair idea that my browsing was causing some damage to my time management but I was not sure as to how much damage it was causing.

To rectify this, I took it upon myself to create a simple application in .Net (C#) which would keep track of time. Initially I thought, let it run in my system tray and manually enter tasks one by one and the time on which I was working on it. It was a realistic idea but not for me, like i said, my laziness was getting to me and I wanted a way to automatically start accounting for the work I do in my computer.

The only way I could this was to write an application which keeps track of all the process running in my Laptop and and keep writing to an XML file. Then I will have to classify these processes using tags and generate a report based on that. I am still not sure how to account for the non-pc work I do but nevertheless this is a start for me. The things I want to keep track of is as follows

  1. Programming Work In Office
  2. Documentation Work In Office
  3. Programming Work at Home
  4. Documentation work at home
  5. Internet Browsing
    1. Track each site i visit and how long i stay there.
    2. Possibly how much was download for the duration that i stayed in the site.
  6. Reading work I do.
  7. Weekly meetings.

That’s it for now. I will soon post a list of feature that I am going to have in the initial version of the tool.

VN:F [1.8.1_1037]
Rating: 0.0/10 (0 votes cast)
VN:F [1.8.1_1037]
Rating: 0 (from 0 votes)
Share and Enjoy:
  • Digg
  • Google Bookmarks
  • del.icio.us
  • Furl
  • LinkedIn
  • Live
  • Reddit
  • StumbleUpon
  • TwitThis
  • Yahoo! Buzz
  • YahooMyWeb

Leave a Comment