82
Date-Time 6793 Visual Basic 6 Tutorials The small and concise lessons of this VB6 tutorial site will help you learn the Visual Basic 6.0 language most effectively, and the sample programs given in the lessons enable practical learning so that you can achieve the potential to develop your own software. Table of Contents:- Lesson 1: Introduction Lesson 2: Starting Visual Basic Lesson 3: The Integrated Development Environment Lesson 4: An overview of VB controls Lesson 5: Your first Visual Basic program Lesson 6: Concept of event driven programming Lesson 7: Variables and data types Lesson 8: Scope of a variable Lesson 9: Operators & expressions Lesson 10: How to make an executable(.exe) file Lesson 11: Naming Conventions Lesson 12: Common properties Lesson 13: Label & TextBox Lesson 14: The CommandButton control Lesson 15: Input and Output operations Lesson 16: Data type conversion Lesson 17: If Blocks Lesson 18: Nested If-Else Lesson 19: Select Case blocks Lesson 20: Do Loops Lesson 21: For...Next Loops

vb.docx

  • Upload
    prachi

  • View
    219

  • Download
    1

Embed Size (px)

DESCRIPTION

study of vb

Citation preview

Date-Time 6793 Visual Basic 6 Tutorials The small and concise lessons of this VB6 tutorial site will help you learn the Visual Basic 6.0 language most effectively, and the sample programs given in the lessons enable practical learning so that you can achieve the potential to develop your own software.

Table of Contents:- Lesson 1: IntroductionLesson 2: Starting Visual BasicLesson 3: The Integrated Development EnvironmentLesson 4: An overview of VB controlsLesson 5: Your first Visual Basic program Lesson 6: Concept of event driven programmingLesson 7: Variables and data typesLesson 8: Scope of a variable Lesson 9: Operators & expressionsLesson 10: How to make an executable(.exe) file Lesson 11: Naming ConventionsLesson 12: Common properties Lesson 13: Label & TextBoxLesson 14: The CommandButton controlLesson 15: Input and Output operations Lesson 16: Data type conversionLesson 17: If Blocks Lesson 18: Nested If-ElseLesson 19: Select Case blocksLesson 20: Do LoopsLesson 21: For...Next LoopsLesson 22: OptionButton & FrameLesson 23: The CheckBox ControlLesson 24: Graphical style of OptionButton & CheckBoxLesson 25: Image & PictureBox Lesson 26: Common events Lesson 27: Control flow functionsLesson 28: Form TemplatesLesson 29: The Form eventsLesson 30: Mouse Hover effectLesson 31: Line & ShapeLesson 32: Important methodsLesson 33: The Object BrowserLesson 34: Numeric FunctionsLesson 35: Formatting FunctionsLesson 36: String ConcatenationLesson 37: String functions Lesson 38: Working with date and timeLesson 39: Data inspection functionsLesson 40: The ListBox ControlLesson 41: Multiple selection feature of the listbox controlLesson 42: The ComboBox ControlLesson 43: Scroll barsLesson 44: DriveListBox, DirListBox & FileListBoxLesson 45: Fixing the overflow errorLesson 46: Animation - The Timer ControlLesson 47: Working with numbersLesson 48: Named constantsLesson 49: Date-time functionsLesson 50: ArrayLesson 51: Multi-dimensional arraysLesson 52: Dynamic ArrayLesson 53: Control ArrayLesson 54: Collection [Part 1]Lesson 55: Collection [Part 2]Lesson 56: Using the data types [Part 1]Lesson 57: Using the data types [Part 2]Lesson 58: User-Defined Type (UDT)Lesson 59: Sub Procedures [Part 1]Lesson 60: Sub Procedures [Part 2]Lesson 61: Function ProceduresLesson 62: MenusLesson 63: Popup Menu Lesson 64: Using multiple formsLesson 65: Splash screenLesson 66: MDI formsLesson 67: The Screen ObjectLesson 68: Standard BAS moduleLesson 69: ValidationLesson 70: Error HandlingLesson 71: The Clipboard Object

Like my facebook page: www.facebook.com/vbtutes for free updates!Functions Lesson 49

There are many useful functions for the date-time operations in VB6. Visual Basic gives you enough power for handling the date and time. Here youll learn about those functions in brief.

This post will include the functions that are defined in the DateTime module of the VBA library. Search DateTime in Object Browser.

WeekdayThe weekday function returns the day of the week. It returns a number representing the day.

Syntax:Variable = weekday(Date, [FirstDayOfWeek])

This function takes two arguments, one is the optional. You need to pass a date string to this function, and the first day of week which is optional is set to vbSunday by default.

The constant values of FirstDayOfWeek paramenter are as follows:vbSundayvbMondayvbTuesdayvbWednesdayvbThursdayvbFridayvbSaturdayvbUseSystemDayOfWeek

Example:Print Weekday("1/4/2014")

Output: 7

YearThe year function returns the year from the date.

Example:Print Year("1/4/2014")

Output: 2014

MonthThe month function returns the month of the year.

Example:Dim m As Integerm = Month("27 / 3 / 2013")MsgBox m

Output: 3

DateValueThe DateValue function returns the date part from a date/time value.

Example:Dim dt As Datedt = DateValue(Now)Print dt

Output: 1/4/2014

TimeValueReturns the time part from a date/time value.

Example:Dim dt As Datedt = TimeValue(Now)Print dt

Output: 12:51:25 PM

DayReturns the day part from a date

Example:Dt = Day(Now)

HourReturns the hour of the day.

Example:Print Hour(Now)

MinuteReturns the minute of the hour.

Example:Print Minute(Now)

SecondReturns the second of the minute.

Example:Print Second(Now)

DatePartReturns a specific part from a date.

Syntax:DatePart(Interval, Date, [FirstDayOfWeek], [FirstWeekOfYear])

The interval parameter is the interval part of a date you want.Pass a date value through the Date parameter.FirstDayOfWeek and FirstWeekOfYear are optional parameters, the values of which are vbSunday and vbFirstJan1

Example:Print "year = " & DatePart("yyyy", "4/1/2014")Print "month = " & DatePart("m", Now)Print "day = " & DatePart("d", Now)Print "week = " & DatePart("ww", Now)Print "hour = " & DatePart("h", Now)Print "minute = " & DatePart("n", Now)Print "second = " & DatePart("s", Now)Print "weekday = " & DatePart("y", Now)

The interval values can be:yyyy-Year,m- Month,d-Day,ww-Week,h-Hour,n-Minute,s-Second,y-weekday.

DateSerialReturns a Date for a specific year, month and day.

Example:Print DateSerial(2014, 1, 4)

TimeSerialReturns a time for a specific hour, minute and second.

Example:Print TimeSerial(13, 15, 55)

DateDiffReturns the number of time intervals between two dates.

Example:dt = DateDiff("d", "5 / 5 / 1990", "26 / 4 / 2013")The first argument is the interval which can have the value among the interval constants mentioned above.

Related topics: Working with date and time Formatting functions Using the data types - Part 1 Using the data types - Part 2

Like my facebook page:www.facebook.com/vbtutesfor free updates!

Newer Post Older Post Home

Main Menu Home Visual Basic 6 Tutorials VB6 Code Samples Visual Basic 2010 Samples Blog

Blog Articles6 Effective Ways to Learn Visual BasicProgramming with Visual Basic for a LivingGuide to Good Programming HabitsComparison between VB6 and VB.NET5 Reasons Why VB is a Good Choice for Making Business Solutions

Google+ Followers

Top of FormGet weekly updatesEmail Address

Bottom of Form

xml search

Array in Visual Basic 6 Lesson 50

An array is a collection of items of the same data type. All items have the same name and they are identified by a subscript or index. When you need to work with several similar data values, you can use array to eliminate the difficulties of declaring so many variables. For example, if you want to compute the daily sales and sum the sales amount after 30 days, you don't need to have 30 variables. Just simply declare an array of size 30 and get your work done !

Declaring an arraySyntax: Dim Variable_Name(index) As [Type]

Example:Dim month(10) As Integer '11 elements'orDim month(1 to 12) as Integer '12 elements

In the first line, month(10) is a collection of 11 integer values or items. month(0) is the 1st item and month(10) is the 10th & last item of the array. So 0 and 10 are respectively the lower bound and upper bound of the array.

In the other line, month(1 to 12) is a collection of 12 integer values or elements or items where month(1) is the 1st item and month(12) is the last. So 1 and 12 are respectively the lower bound and upper bound of the array.

Types of arrayThe array used in the example is a one-dimensional and fixed-size array. An array can have more than one dimension. The other types of arrays are multi-dimensional arrays, Dynamic arrays and Control arrays.

Fixed-Size Array:We know the total number of items the array in the above example holds. So that is a Fixed-Size array.

The LBound and UBound functionsThe LBound and Ubound functions return the lower bound and upper bound of an array respectively.

Example: Private Sub cmdDisplay_Click() Dim arr(10) As Integer a = LBound(arr) b = UBound(arr)

MsgBox "Lower bound = " & a & " Upper bound = " & b

End Sub

Initializing an arrayYou can use For Loop to initialize an array.

Example:Dim day(10) As Integer, i As IntegerFor i = 0 To 10 day(i) = InputBox("Enter day value")Next i

You can also initialize each array item separately in the way a variable is initialized.

Example: This program inputs the Sale amount of each day and sums the total amount of 5 days. Private Sub cmdStart_Click() Dim SaleDay(1 To 5) 'Sale in a particular day Dim i As Integer, Sale As Long Sale = 0

For i = 1 To 5 SaleDay(i) = InputBox("Enter Sale amount of Day " & i) Sale = Sale + SaleDay(i) Next i

MsgBox "Total Sale of 5 days = $" & Sale

End Sub

Related topics: Multi-dimensional array Dynamic array Control array CollectionMulti-Dimensional Arrays Lesson 51

An array can be multi-dimensional that means, it can have more than one dimension. A list of data is represented in a one-dimensional array where a multi-dimensional array represents a table of data. An array can be two dimensional, three dimensional and so on. We generally don't need an array of more than two dimensions, it is enough to use one and two dimensional arrays. You can use a higher dimensional array when the program is too complex. A two dimensional array takes the row-column form.

Declaration:Dim value(5, 5) As Integer 'two dimensional'Or,Dim value(1 to 5, 1 to 5) As DoubleDim number(6, 9, 8) As Integer 'three dimensinoal

Initialization:To initialize the array elements, you first need to recognize the array elements. For example, the array 'value(2, 2)' has 9 elements. They are value(0,0), value(0,1), value(0,2), value(1,0), value(1,1), value(1,2), value(2,0), value(2,1), value(2,2). For the initialization, you may wish to use For Loop or initialize each element like variables. Using For Loop is a better choice as it reduces the number of lines of code. But sometimes, separately initializing each element like a variable is much more convenient. And it also depends on the type of program you are writing .

Addition of 2D matrices : Example of a two dimensional arrayExample: Private Sub cmdSum_Click() Dim matrix1(1, 1) As Integer, matrix2(1, 1) As Integer Dim sum(1, 1) As Integer

'initializiation of matrix1 matrix1(0, 0) = Val(Text1.Text) matrix1(0, 1) = Val(Text2.Text) matrix1(1, 0) = Val(Text3.Text) matrix1(1, 1) = Val(Text4.Text)

'initializiation of matrix2 matrix2(0, 0) = Val(Text5.Text) matrix2(0, 1) = Val(Text6.Text) matrix2(1, 0) = Val(Text7.Text) matrix2(1, 1) = Val(Text8.Text)

'Summation of two matrices For i = 0 To 1 For j = 0 To 1 sum(i, j) = matrix1(i, j) + matrix2(i, j) Next j Next i

'Displaying the result Print "The resultant matrix" For i = 0 To 1 For j = 0 To 1 Print sum(i, j); Next j Print "" Next iEnd Sub

Sample program: Matrix Addition

Related topics: Array Control array Dynamic array Collection

Dynamic Array Lesson 52

In case of a fixed size array, we have seen that the size of the array is fixed or unchanged, but there may be some situations where you may want to change the array size. A dynamic array can be resized at run time whenever you want.

Declaring dynamic arrays1. Declare the array with empty dimension list.Example : Dim arr() As Integer2. Resize the array with the ReDim keyword.Example : ReDim arr(5) As Integeror, ReDim arr(2 To 5) As Integer

Example:Dim ar() As IntegerReDim ar(2) As Integer

Note: Unlike the Dim and Static statements, the ReDim statements are executable. So a ReDim statement can only be in a procedure and when you execute the ReDim statement, all the values stored in the array are lost. You can use the ReDim statement repeatedly to change the array size.

Preserving the values of Dynamic arraysThe ReDim statement deletes all the values stored in the array. You can preserve the element values using the Preserve keyword. So using Preserve keyword with ReDimstatements enables you to change the array size without losing the data in the array.

Example:Dim arr() As IntegerReDim arr(2) As Integer

For i = 0 To 2 arr(i) = InputBox("Enter the value")Next i

ReDim Preserve arr(3) As Integerarr(3) = 9Print arr(0), arr(1), arr(2), arr(3)

Output: If the input values through InputBox are 5,6,7 then the following will be printed on the form.5 6 7 9

Related topics: Array Multi-dimensional array Control array Collection- part 1 Collection - part 2 User-define type (UDT)

Dynamic Array Lesson 52

In case of a fixed size array, we have seen that the size of the array is fixed or unchanged, but there may be some situations where you may want to change the array size. A dynamic array can be resized at run time whenever you want.

Declaring dynamic arrays1. Declare the array with empty dimension list.Example : Dim arr() As Integer2. Resize the array with the ReDim keyword.Example : ReDim arr(5) As Integeror, ReDim arr(2 To 5) As Integer

Example:Dim ar() As IntegerReDim ar(2) As Integer

Note: Unlike the Dim and Static statements, the ReDim statements are executable. So a ReDim statement can only be in a procedure and when you execute the ReDim statement, all the values stored in the array are lost. You can use the ReDim statement repeatedly to change the array size.

Preserving the values of Dynamic arraysThe ReDim statement deletes all the values stored in the array. You can preserve the element values using the Preserve keyword. So using Preserve keyword with ReDimstatements enables you to change the array size without losing the data in the array.

Example:Dim arr() As IntegerReDim arr(2) As Integer

For i = 0 To 2 arr(i) = InputBox("Enter the value")Next i

ReDim Preserve arr(3) As Integerarr(3) = 9Print arr(0), arr(1), arr(2), arr(3)

Output: If the input values through InputBox are 5,6,7 then the following will be printed on the form.5 6 7 9

Related topics: Array Multi-dimensional array Control array Collection- part 1 Collection - part 2 User-define type (UDT)

Control Array Lesson 53

Till now we have discussed array of variables. Similarly you can also have an array of controls by grouping a set of controls together. The controls must be of the same type like all TextBoxes or all CommandButtons.

Creating control arrays1.Place some same type of controls say CommandButtons on the form. Make their name properties same and then a warning (see picture below) dialog box will come asking whether you want to create a control array, click Yes.

Or, after placing a control on the form, copy that and paste on the form. It will create control array for you.

2. Set the Index property of each control or you may not change as it is automatically set.

3. Now its done. You are ready to use the control array in your code.

Using control arraySyntax to refer to a member of the control array : Control_Name(Index).Property

Example: Set the Style property of Command1(1) to 1 to work with the BackColor property. Private Sub Command1_Click(Index As Integer) Command1(1).BackColor = vbGreenEnd Sub

Example: Create a control array of 5 CommandButton controls and then set their Style property to 1.Private Sub Command1_Click(Index As Integer) Dim i As Integer

For i = 0 To 4 Command1(i).BackColor = vbBlue Next iEnd Sub

You can also pass a value to the Index parameter from other procedures.

Control array is useful when you want to clear a set of TextBox fields. Create a control array of 5 TextBox controls and write the following code in the Click event procedure of a CommandButton control.

Example:Private Sub cmdClearAllFields_Click() Dim i As Integer

For i = 0 To 4 'Or, For i=Text1.LBound To Text1.UBound Text1(i).Text = "" Next iEnd Sub

Output:

Sharing Event procedures Create a control array of some command buttons with the name "Command1". Note that Visual Basic automatically passes the Index parameter value. So the following code will work for all controls in the control array. You don't need to write code for all the CommandButton controls. Click on any CommandButton, the following single block of code will work for all.

Example:Private Sub Command1_Click(Index As Integer) Command1(Index).BackColor = vbBlackEnd Sub

Creating controls at run-timeOnce you have created a control array, you can create controls at run-time using the Load command.

Example: First of all, create Text1(0) and Text1(1) at design time.Private Sub Command1_Click() Load Text1(2)

'Move the control where you want Text1(2).Move 0, 100

Text1(2).Visible = TrueEnd Sub

On clicking the Command1 button, a new TextBox control will be created. You can remove any control from the control array using the Unload command.Unload Text1(2)

Related topics: Array Multi-dimensional array Dynamic array Collection - part 1 Collection - part2 User-defined type

Collection [Part 1] in Visual Basic 6 Lesson 54

Collections are objects in Visual Basic that are used to store a group of data values. Collections are similar to array. But there are some special features that differentiate the collections from arrays.

We have seen that array elements must be of the same data type. But the Collection members can be of any data type and you don't need to set the size of the Collection object. You can easily add items to the collection and it will grow accordingly.

Creating a CollectionTo use a Collection in your code, you first need to declare and create it.

Example:Dim names As Collection 'Declaring the CollectionSet names = New Collection 'Creating the Collection

Or, replace the above code with this one line codeDim names As New Collection 'Declaration and creation

Adding items to a Collection : The Add methodYou can add one item at a time using the Add method.

Example:Dim names As New Collection

names.Add "john"names.Add "david"

You may use a string key associated with the item. The string key is used to refer to a Collection item.Dim names As New Collection

names.Add "John", "one" ' "one" is the string key, used to refer to the item

Retrieving item values : The Item methodYou can refer to a particular item of the collection using the Item method. Here you may use either the index or key value. The index value starts from 1.Syntax : Collection_Name.Item(Index)or, Collection_Name.Item(Key)

Example: Retrieving a particular item using the index of the itemPrivate Sub cmdShow_Click() Dim names As New Collection

names.Add "John", "one" names.Add "David"

Print names.Item(2) '2 is the index of the item

End Sub

Output: David

Example: Retrieving a particular item using the string key of the itemPrivate Sub cmdShow_Click() Dim names As New Collection

names.Add "John", "one" names.Add "David"

Print names.Item("one")

End Sub

Output: John

The Item method is the default member of the Collection class, so you may omit it in your code.

Example:Private Sub cmdShow_Click() Dim names As New Collection

names.Add "John", "one" names.Add "David"

Print names("one") Print names(2)

End Sub

Output:JohnDavid

Related topics: Array Multi-dimensional array Dynamic array Control array User-defined type

Collection [Part 2] - Visual Basic 6 Lesson 55

Using the Before and After argument of the Add methodYou can choose to store the item values exactly where you want using the Before and After argument of the Add method.

Example:Private Sub cmdShow_Click()

Dim items As New Collection

items.Add "one" items.Add "two" items.Add "three", , 1

For i = 1 To 3 Print items.Item(i) Next iEnd Sub

Output:threeonetwo

Removing an item : The Remove methodYou can remove a particular item from the Collection using the Remove method.

Example:Private Sub Command1_Click() Dim country As New Collection country.Add "USA" country.Add "UK" country.Add "Japan", "j"

country.Remove (1) country.Remove ("j")

End Sub

Number of items in a Collection : The Count methodExample:Private Sub cmdCount_Click() Dim country As New Collection country.Add "USA" country.Add "India" country.Add "Japan", "j"

Dim n As Integer n = country.Count Print n

End Sub

Output: 3

Retrieving the last itemExample: Private Sub Command1_Click() Dim country As New Collection country.Add "Germany" country.Add "India" country.Add "China", "j"

Print country.Item(country.Count)End Sub

Output: China

Deleting all items from the CollectionUse a Do While loop to delete all item from the Collection object.

Example: Private Sub cmdDeleteAll_Click() Dim country As New Collection country.Add "Bangladesh" country.Add "Australia" country.Add "Russia", "j"

Do While (country.Count > 0) country.Remove 1 Loop

Print country.CountEnd Sub

Output: 0

Another way to delete all items is to destroy the Collection object. The following code destroys the Collection object and thus deletes all the items.Set items = Nothing'Or,Set items = New Collection

Related topics: Array Multi-dimensional array Dynamic array Control array User-defined type

Like my facebook page:www.facebook.com/vbtutesfor free updates!

Add Form > Form. Public general sub procedures are useful when want to invoke your procedure from wherever you want, from any module.

Example:'In Form1Private Sub Command1_Click() Call Form2.xprintEnd Sub

'In form2

Public Sub xprint() Form2.Show Print "Hello World !" Print ""; Print "***" Print "New"End Sub_____________________________________________________________Private Sub Command1_Click() Call xprintEnd Sub

The concept of Public general sub procedure will be clearer to you when you'll learn about working with multiple forms in the next chapters.

Related topics: Sub procedures - Part 1 Scope of a variable Function procedures Standard BAS module

Like my facebook page:www.facebook.com/vbtutesfor free updates!Function Procedures Lesson 61

A function procedure in Visual Basic 6 has a scope, a unique name, parameter list and return value. You can pass any datatype to a procedure e.g Integer, Boolean, Long, Byte, Single, Double, Currency, Date, String and Variant. Object data types and arrays are also supported. This is same for the return type values.

Difference between argument and parameterThe value you're passing, while calling the function, is called argument and the variable, in the function definition, that will receive the value is called parameter. Both the terms are used for the same value.

A function procedure may not return a value.

Example: In this example, 32 and 54 are passed to the function 'sum' from Form_Load procedure.'Function Definition Private Function sum(n1 As Integer, n2 As Integer) 'n1, n2 are 'parameters Text1.Text = n1 + n2End Function__________________________________________________________________Private Sub Form_Load() Text1.Text = "" 'Function callgin Call sum(32, 54) '32 and 54 are arguments End Sub

Output:

Function procedure that returns valueExample:'Function Definition Private Function sum(n1 As Integer, n2 As Integer) As Integer 'Returns a value sum = n1 + n2End Function____________________________________________________________Private Sub Form_Load() Text1.Text = "" 'Function calling and assigning the returned value Text1.Text = sum(60, 40) End Sub

Passing arguments: By Value or By ReferenceYou can pass an argument either by value or by reference. Arguments are passed by value using the ByVal keyword and by reference using the ByRef keyword or by omitting any specifier.

While passing the arguments by reference, references of the variables are passed. So if the argument is passed by reference, it can be modified by the called procedure and the original value of the argument in the calling procedure will be changed. But the argument value will be unchanged if you call the procedure using constants or expressions as parameters.

Example:'Calling procedurePrivate Sub Command1_Click() Dim a As Integer 'The value of a is 0 after declaration Call num(a)

Print a 'Value of a is 1, modifiedEnd Sub___________________________________________________________________'Called procedurePublic Function num(ByRef x As Integer) 'You may omit ByRef x = x + 1End Function

On the other hand, when the arguments are passed by value, the actual values are passed. So the called procedure cannot change their original values in any way.

Example:'Calling procedurePrivate Sub Command1_Click() Dim a As Integer 'The value of a is 0 after declaration Call num(a)

Print a 'The value of a is 0, its unchangedEnd Sub___________________________________________________________________'Called procedurePublic Function num(ByVal x As Integer) x = x + 1End Function

Note: Both Sub and Function procedures can accept parameters.

Related topics: Sub procedures - Part 1 Sub procedures - Part 2 Standard BAS module Scope of a variable

Like my facebook page:www.facebook.com/vbtutesfor free updates!How to Add a Menu to Your VB6 Program Lesson 62

Menus are one of the most important features of a software product. Every standard software must have menus. You generally see a menu on top of a software interface. Menus are controls but different from the controls in the ToolBox and they don't work like the other controls. You can drop a menu on the form from the Menu Editor Window. Press Ctrl+E to show the Menu Editor Window or right-click on the form and click Menu Editor. The Menu Editor Window can also be shown from the Menu Editor icon of the ToolBar.

Building a menuBuilding a menu is very simple, you can do it on your own. Simply fill the Caption and Name field in the Menu Editor Window and click ok to create it.

Click the right-arrow button to create a submenu. Click Next to create the next menu item, and click ok once you're done editing the menu items.

A simple form with menu:

Properties of the menu itemsThe important properties of the menu items are Name, Caption, Checked, Enabled, Shortcut and Visible. As per your programming need, set the properties either in run-time or in design time. You can create a shortcut key for a menu item. In some situations you may want to disable a menu item, you can acquire it through the Enabled property.

The menu control exposes only one event, the Click event.

Example: Make a menu as same as the following image.

Now write the following code.Private Sub mnuBlue_Click() Form1.BackColor = vbBlue 'Makes the Form blueEnd Sub______________________________________________________________Private Sub mnuGreen_Click() Form1.BackColor = vbGreen 'Makes the form greenEnd Sub______________________________________________________________Private Sub mnuRed_Click() Form1.BackColor = vbRed 'Makes the form redEnd Sub______________________________________________________________Private Sub mnuWhite_Click() Form1.BackColor = vbWhite 'Makes the form whiteEnd Sub

Now run the program and Click on the menu items and see what happens.

The Checked propertyDesign a form like the output image of the following program. Create a Help menu and drop a Label control on the form with the caption 'Help'.

Now write the following code.Private Sub mnuShowHelp_Click() If mnuShowHelp.Checked = True Then mnuShowHelp.Checked = False Label2.Visible = False ElseIf mnuShowHelp.Checked = False Then mnuShowHelp.Checked = True Label2.Visible = True End IfEnd Sub

Output:

Related topics: Popup menu CheckBox control

Like my facebook page:www.facebook.com/vbtutesfor free updates!

Add Form from the menu bar and select splash screen. Then modify the form as per your needs.2. The other way is, add a form to your existing project. Set the BorderStyle property to None. Then edit the form according to your choice.

Working with the splash screen1. Take a timer on the splash screen form. Set the interval to some seconds, for example 3 seconds. Then you need to set the Timer's Interval property to 3000.2. Write the following code in the Timer's Timer Event. Suppose the form you want to load after the splash screen is frmMain.

Private Sub Timer1_Timer() Timer1.Enabled = False frmMain.Show Unload MeEnd Sub

On executing the code, the splash screen stays for 3 seconds and then the Main Window is shown after the splash form is unloaded.

Related topics: Using multiple forms MDI forms

Like my facebook page:www.facebook.com/vbtutesfor free updates!

Add Module. Click Project menu from the menu bar and select add module.

A separate project file with the .bas extension is saved on your hard disk as soon as you add a standard module to your current project. You can change the Name property of your newly added standard module from the properties window. Choose a meaningful name, it will benefit you while writing the code.

The modules are shown in project explorer window:

Contents of the standard module:1. Procedure definitions2. Variable, type and constant declarations.

The variables and constants declared using the Public keyword in the Declrations section of the module are global, accessible from all parts of your current application.

An easy example:'Inside the BAS Module

'Scope is Public to make it accessible from anywhere of the applicationPublic Sub show() MsgBox "Welcome to vbtutes" MsgBox "This is a message" MsgBox "New message!" MsgBox "List of messages"End Sub__________________________________________________Public Function increment(number As Integer) As Integer increment = number + 1End Function

'In form1Private Sub cmdShow_Click() Dim num As Integer Dim m As Integer num = InputBox("Enter the number", "Input") m = Module1.increment(num) MsgBox m Call Module1.show

End Sub

' In Form2Private Sub Form_Load() Call Module1.showEnd Sub

' In Form3 'The show sub procedure is global

Private Sub Form_Load() Call Module1.showEnd Sub

Note: BAS modules are especially useful in large projects. So if you're developing a big VB6 application, include them.

Related topics: Multiple forms MDI forms

Like my facebook page:www.facebook.com/vbtutesfor free updates!

Validation in Visual Basic 6 Lesson 69

Today I'll show you the techniques of validation in VB6. Validation is a very useful feature of VB6 which you implement not only in the registration and login forms but also in a variety of situations. Many applications have login systems. So while designing the login and registration forms, it is a must to include the validations for the controls on the forms.

What is validation? You must have noticed in many applications that when you enter a data incorrectly or when you leave the field blank, it warns you with a message. This is called validation.

More precisely, when you leave the text field and move to another control, you get a warning message and the input focus goes back to the previous field.

Examples:

I have already shown you an example of this type in the Registration program sample, but VB6 validation techniques were not used in that sample. You may say that you can do it without using the validation code, but VB6 provides a better way, a more convenient way to achieve the same which is obviously the better solution to the problem.

The Validation event and the CausesValidation property makes the solution working together. And sometimes the ValidateControls method is required. That's all.

The default value of the CausesValidation property is True, and most of the controls, even the external controls, support this property.

You have to write the code in the Validate event of the control where you input the data, may be the TextBox control. After that you move to another control, may be a CommandButton, a TextBox or any other. That means the first control where you entered the data lost the input focus, and the other control is about to recieve the focus. If the CausesValidation property of the control, which is about to recieve the focus, is True only then Visual Basic fires the Validate event of the first control that lost the focus.

Example:Take two TextBox controls, a submit button; set their CausesValidation property to True. Take a Cancel button, set its CausesValidation property to False.

Set the TabIndex value of the txtName control to 0.

Download this sample.

Private Sub txtName_Validate(Cancel As Boolean) If txtName.Text = "" Then MsgBox "Please enter your name!", vbExclamation, "" Cancel = True End IfEnd SubWhen the Cancel parameter is True, the input focus goes back to the txtName control.

Private Sub txtPhone_Validate(Cancel As Boolean) If Len(txtPhone.Text) < 10 Then MsgBox "Enter the phone number in 10 digits!", vbExclamation, "" Cancel = True End IfEnd SubIn this case, the input focus moves back to the txtPhone control when the the Cancel parameter is set to True.

The IsNumeric functionWhat if the user enters a non-numeric i.e a string value in the txtPhone field? So now you may want your users only to enter numeric values there. The IsNumeric function can do it for you.

It returns True if it is a numeric value.If Not IsNumeric(txtPhone.txt) Then Cancel = TrueEnd If

The ValidateControls methodYou generally use this method so that the user cannot close the form without validating first.

This method invokes the Validate event of the control which has the input focus. You generally use it in the Unload or QueryUnload event prcedure.

Private Sub Form_Unload(Cancel As Integer) On Error Resume Next ValidateControls If Err = 380 Then Cancel = True End IfEnd Sub

This method returns an Error 380 in the case when the cancel paramter was set to True in the Validate event procedure of the control having the input focus.

Download this sample here.

Related topics: Form events TextBox control

Like my facebook page:www.facebook.com/vbtutesfor free updates!

2402218Google +0206 Error Handling in Visual Basic 6 Lesson 70

In this lesson, I'll talk about error handling in Visual Basic 6. I will discuss, in brief, how you can handle errors in your Visual Basic program. I'm not going to give you an in-depth concept of error handling. Because that is beyond the scope of this text which is targeted to the beginner learners. But I will discuss a few features of Visual Basic 6 that enable you to efficiently manage the errors in your program.

Related topic: Fixing the overflow error

See the following pages for more tutorials: Visual Basic 6 tutorials VB6 code samples VB2010 sample projects

What happens when error occurs?When an error is encountered in your program, the program stops running showing an error message in a dialog box. So this is going to be a real problem if you cannot find the bug.

For example, say, you have developed a software. And also say, there's a bug, an error. Then while using your software, the end-user will face the problem. The program will stop running reporting an error. So you have to find a solution to this problem.

How to deal with bugs?So as I said you have to find a solution to this problem, there are some options at your hand. You either have to programmatically ignore the error or display a warning message to the end-user or find the bug and debug your program.

Error handling statementsSome useful error handling statements are there in Visual Basic 6 which help you ignore, bypass or handle errors in your program. Three such statements are helpful. They are as follows: On Error Resume Next statement:If any error occurs, it is ignored, and the control goes to the next statement. On Error Goto label:If any error occurs, the control jumps to a label. On Error Goto 0:This statement cancels the effect of 'On Error Resume Next' and 'On Error Goto label' statements.

On Error Resume NextIf Visual Basic encounters an error, it ignores the error. Then the control goes to the next statement. More precisely, Visual Basic causes a jump to the next statement. And Visual Basic executes the statements ignoring the statement where the error is found. Consider this example.

Example:On Error Resume Nexta = 6 / 0

Print "hello"

On Error Goto labelIf Visual Basic encounters an error in a statement, the On Error Goto label statement tells Visual Basic to jump to the named label. Thus the control jumps to the named label. Then the code following the named label is executed. Consider the following example.

Example:On Error GoTo AA = 6 / 0

A:Print "hello"Print "Welcome"

On Error Goto 0On Error Goto 0 statement tells Visual Basic to cancel any effect of 'On Error Resume Next' and 'On Error Goto label' statements. So this statement cancels the effect of errorhandling in your program.

The Err functionThe Err function can help you handle the error using the error code. For example, you can display a warning message to the end-user. The following example clarifies this.

Example:On Error Resume Nextb = 88 / 0

If Err = 11 Then MsgBox "Error: Division by zero!"End If

Example:On Error GoTo Label5b = 88 / 0

Label5:If Err = 11 Then MsgBox "Error: Division by zero!"End If

Related topic: Fixing the overflow error

See the following pages for more: Visual Basic 6 tutorials VB6 code samples VB2010 sample projects

Like my facebook page:www.facebook.com/vbtutesfor free updates!

The Clipboard Object in VB6 Lesson 71

The clipboard object is a simple object in Visual Basic 6 that stores data. You can retrieve the data from the clipboard using appropriate methods of the clipboard object.

In the Windows operating system, when you copy some data, the data is automatically copied or stored in the clipboard object. You can place data in the clipboard object and retrieve the data from clipboard.

Visual Basic study materials: Visual Basic 6 tutorials VB6 code samples VB2010 sample projects

You can easily copy and paste data among applications - from one application to another using the clipboard object.

The clipboard object has no properties. It has a few methods that help you work upon the data.

Download this sample: Copy-paste sample

The SetTex methodThe SetTex method puts text in the clipboard. In other words, you can place text in the clipboard object using this method.

Example:Clipboard.SetText Text1.Text

The Clear methodThe Clear method clears the clipboard.

Example:Clipboard.Clear

The GetTex methodThe GetTex method lets you retrieve the text which is in clipboard.

Example:Text2.Text = Clipboard.GetText

The SetData methodThe SetData method places data e.g an image in clipboard.

Example:Clipboard.SetData Picture1.Picture' orClipboard.SetData LoadPicture("d:\mypic.bmp")

The GetData methodThe GetData method retrieves data, for example an image, from the clipboard object.

Example:Picture2.Picture = Clipboard.GetData

Download sample: Copy-paste sample

Tutorials: Control flow functions The Form events Fixing the overflow error The Screen object More >>>>>>>

Code samples: Calculator Number system converter Photo Viewer Contacts Manager More >>>>>>>>>

Blog articles you may like: 6 Effective Ways to Learn Visual Basic 5 Reasons Why VB is a Good Choice for Making Business Solutions Guide to Good Programming Habits Comparison between VB6 and VB.NET