visual basic notes

51
Front-End And Back-End Form / Interface / Front-End Student Roll Number Name Address Phone 1 Raj c-65, hari nagar 25126633 2 Amit a-45, Ramesh ngr. 25165263 3 Rahul c-96, Janak puri 25545298 Table / Relation / Back-End DataTypes in VB Roll Number Name Address Phone 4 Himanshu WZ-45, Hari Nagar 9213222920 Save Dele te Searc h

Upload: ashish

Post on 14-Nov-2014

36 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: visual basic notes

Front-End And Back-End

Form / Interface / Front-End

StudentRoll Number Name Address Phone1 Raj c-65, hari nagar 251266332 Amit a-45, Ramesh ngr. 251652633 Rahul c-96, Janak puri 25545298

Table / Relation / Back-End

DataTypes in VB

Datatype Storage size Range 1. Byte 1 byte 0-2552. Boolean 2 bytes True or False3. Integer 2 bytes -32768 to +327674. Long 4 bytes -2147483648 to +2147483647 5. Single 4 bytes

Roll Number

Name

Address

Phone

4

Himanshu

WZ-45, Hari Nagar

9213222920

Save Delete Search

Page 2: visual basic notes

6. Double 8 bytes7. Currency 8 bytes8. Decimal 14 bytes9. Date 8 bytes Jan 1, 100 to

Dec 31, 999910. Object 4 bytes Any object reference11. String (variable length) 10 bytes + string length 0 to approx. 2 billion12. String (fixed length) length of string 1 to approx. 65,400 13. Variant (numeric) 16 bytes 14. Variant (text) 22 bytes + string length

Declaring & initializing Variables

Dim Num as integerNum = 2557

Or Num = -235 Or Num = 32 + 7 - 3

Dim Age as byteAge = 73

Or Age = 12Dim Name as string …. variable length string Name = “raj”Dim Name as string * 15 …. fixed length stringName = “raj”Dim Address as stringAddress = “A-45, janak puri“Dim price as singlePrice = 75.80

Or Price = 75.25 - 1.85Dim x as Booleanx = true

Or x = false Or x= 5<2 …. false

dim doj as datedoj = #8-15-2005#dim x as datex = #12:45 PM#dim p as variant

Or dim p …. (by default variant)p = “raj”

Or p = 45 Or p = #8-15-2005# Or p = true Or p=45.7

Page 3: visual basic notes

Dim a, b, c as integer

Variant variables

Literals

String literals:“raj”, “a-45, hari nagar”, “845.73”, “8-15-2005”

Boolean literals:True, false

Date / Time literals:#8-12-2005#, #1:45 AM #

Single / Double literals:12.5#, -13.80 , +0.73, 85.2!

byte / integer / long literals:+45, -33, 0, 48, 128, 85%

Type declaration characters

% Integer$ string@ currency& long# double! single

Dim x% declares x as integer variableDim p$ declares p as string variableDim n# declares n as double variable

CommentsThe word REM or symbol (‘) tells the visual basic that everything on that line

following REM or (‘) is not the code, it is a comment and should be ignored by the compiler. REM can appear only in the beginning of the line but apostrophe (‘) can appear after a statement also.

Example:Dim x% ‘declares x as integer variable REM example of a comment.

Variable Default Values

Datatype Default Values Integer 0 Long 0 Single 0

Page 4: visual basic notes

Double 0 String “ “ blanks/null Boolean false Variant empty Date 0 Currency 0

Implicit & Explicit Variables Declaration

Dim x, y variant variablesP=100 implicit variable (variant)Dim m as integer explicit variable Option explicit only explicit variables can be used

Defining Named Constants

Syntax:[public / private] const <constantname> [as type] = expression

Examples:const pi = 3.14public const a as integer = 9const jdate = #2/1/05#public const nm = ”raj”public const x = 14, nm = “raj”

Operators1. Arithmetic Operators2. String or Concatenation Operators3. Comparison Operators4. Logical Operators

Arithmetic operators

+, -, *, /, \ , mod, ^2 + 5 …. 7“daljeet” + ”singh” …. “daljeetsingh”“91” + “6” …. “916”5/2 …. 2.511/3 …. 3.665\2 …. 211\ 3 …. 35 mod 2 …. 111 mod 3 …. 22 ^ 3 = 23 …. 83 ^ 3 = 33 …. 27

Page 5: visual basic notes

Concatenation operators(&)“Daljeet“ & “singh“ …. “Daljeetsingh”

Comparison operators= 2=3 …. false< > 9< >7 …. true> 8>5 …. true>= 5>=5 …. true< 91<15 …. false<= 9<=8 …. false

Logical Operators

AND, OR, NOT, XOR(5 > 7 AND 9 <= 81) …. falsefalse true

Truth TableA B A AND B A OR B A XOR B NOT A NOT BFalse False False False False True True False True False True True True FalseTrue False False True True False TrueTrue True True True False False False

The Print StatementSyntax:

Print “Message Text“Print constant / variable / expression

Example:Print “this is visual basic”Print 10A = 30Print APrint A * 2 / 3

Print using comma:Print 2, 3, 4, 5, 6

Output:2 3 4 5 6

Print using semicolon:Print 1;2;3;4

Output: 1234

print “hello“;“friends“Output:

hellofriends

Page 6: visual basic notes

Controls & their Properties

Control Name Property ValueLabel Name

Appearance 0 – flat1 – 3D

Alignment 0 – left justify1 – right justify2 – center

Autosize true / falseBackcolorBackstyle 0 – transparent

1 – opaqueBorderstyle 0 – none

1 – fixed singleCaptionEnabled true / falseFontForecolorHeightLeftTooltiptextTopVisible true / falseWidth

Control name Property ValueTextbox Name

Alignment 0 – left1 – right2 – center

BackcolorEnabled True / falseFontForecolorHeightLeftMaxlengthMultiline True / falsePasswordcharScrollbars 0 – none

1 – horizontal2 – vertical3 – both

Width

Page 7: visual basic notes

Borderstyle 0 – none1 – fixed single

Appearance 0 – flat1 – 3D

TextTooltiptextTopVisible true / false

Control Name Property ValueCommand button Name

Appearance 0 – flat1 – 3D

BackcolorCaptionDisabledpictureDownpictureEnabled true / falseFontHeightLeftPictureStyle 0 – standard

1 – graphicalTooltiptextTopVisible true / falseWidth

Control Name Property ValueFrame Name

BackcolorBorderstyle 0 – none

1 – fixed singleCaptionEnabled true / falseFontForecolorHeightLeftTooltiptextTopVisible true / falseWidth

Page 8: visual basic notes

Control Name Property ValueCheckbox Name

Allignment 0 – left1 - right

BackcolorCaptionDisabledpictureDownpictureEnabled true / falseFontForecolorHeightLeftPictureStyle 0 – standard

1 – graphicalTooltiptextTopValue 0 – unchecked

1 – checkedVisible true / falseWidth

Control Name Property ValueOptionbutton Name

Allignment 0 – left1 - right

BackcolorCaptionDisabledpictureDownpictureEnabled true / falseFontForecolorHeightLeftPictureStyle 0 – standard

1 – graphicalTooltiptextTopValue true / falseVisible true / falseWidth

Page 9: visual basic notes

Control Name Property ValuePicturebox Name

Align 0 - None 1 – Align top2 – Align bottom3 – Align left4 – Align right

Autosize True / falseBackcolorBorderstyle 0 – none

1 – fixed singleEnabled true / falseFontForecolorHeightLeftPictureTooltiptextTopVisible true / falseWidth

Control Name Property ValueImage Name

Borderstyle 0 – none1 – fixed single

Enabled true / falseHeightLeftPictureStretch true / falseTooltiptextTopVisible true / falseWidth

Control Name Property ValueCombo box Name

BackcolorEnabled True / falseFontForecolorHeightLeftList

Page 10: visual basic notes

Style 0 – Drop down combo1 – simple combo2 – drop down list

TextTooltiptextTopVisible true / falseWidth

Control Name Property ValueListbox Name

BackcolorEnabled True / falseFontForecolorHeightLeftListMultiselect 0 – none

1 – simple2 – extended

Style 0 – standard1 – checkbox

TooltiptextTopVisible True / FalseWidthText

Control Name Property ValueHscrollbar / vscrollbar Name

Enabled True / falseHeightLeftMax 32767Min 0TopValueVisible True / falseWidth

Control Name Property ValueDriveListbox Name

BackcolorEnabled True / falseFontForecolorHeight

Page 11: visual basic notes

LeftTooltiptextTopVisible True / falseWidthDrive

Control Name Property ValueDirectory list box Name

BackcolorEnabled True / falseFontForecolorHeightLeftTooltiptextTopVisible True / falseWidthPath

Control Name Property ValueFile list box Name

BackcolorEnabled True / FalseFontForecolorHeightLeftMultiselect 0 – none

1 – simple2 – extended

PatternTooltiptextTopVisible True / falseWidthPath

Control Name Property ValueShape Name

BackcolorBackstyle 0 – transparent

1 – opaqueBordercolorFillcolorHeightLeft

Page 12: visual basic notes

Shape 0 – rectangle1 – square2 – oval3 – circle4 – rounded rectangle5 – rounded square

TopVisible True / falseWidthFillstyle 0 – solid

1 - transparent

Control Name Property ValueTimer Name

Enabled True /FalseIntervalLeftTop

Control Name Property ValueForm Name

BackcolorCaptionEnabled True / falseFontForecolorHeightLeftMdichild True / false Maxbutton True / falseMinbutton True / falsePictureTopVisible True / FalseWidthWindowstate 0 – normal

1 – minimized2 - maximized

Page 13: visual basic notes

Events Event refers to the occurrence of an activity.

Some useful events

1. Click:- When the user clicks the primary mouse button on an object.2. Change:- When the user modifies text in combo box or text box.3. Gotfocus:- When an object receives focus.4. Lostfocus:-When an object loses focus.5. Keypress:- The user presses and releases a keyboard key while an object has

focus.6. Keyup:- When the user releases a keyboard key when an object has focus.7. Dragdrop:- The use drags an object to another location.8. Dragover:- The user drags an object over another control.9. Form_load: - When the form loads for execution in memory.

Setting the Properties

The controls that you draw on your form, have some properties associated with them. The properties can be set by two different ways.

1. At design time2. At run time.

1. Properties can be set at design time using properties window.

2. Setting properties at run time.

Setting the Alignment property

Example:Label1.alignment = 0

OrText1.alignment = 1

Setting Appearance property

Example:Label1.appearance =1

OrCommand1.appearance = 1

OrOption1.appearance = 0

Setting Autosize PropertyExample:

Label1.autosize = true

Page 14: visual basic notes

OrLabel1.autosize = false

OrPicture1.autosize = true

Setting the backcolor propertyExample:

Label1.backcolor = RGB(100, 125, 190)

0-255 (red) 0-255(green) 0-255( blue)Or

text1.backcolor = RGB(50, 50, 100)Or

text1.backcolor = VbRed

Setting Backstyle PropertyExample:

Label1.Backstyle = 0Or

Label1.backstyle = 1

Setting Borderstyle PropertyExample:

Label1.Borderstyle = 0Or

Label1.Borderstyle = 1

Setting the Enabled PropertyExample

Text1.enabled = trueOr

Label1.enabled = false

Setting caption propertyExample:

Label1.caption = “this is my name”Or

Command1.caption = “click me”

Setting forecolor propertyExample:

Label1.forecolor = RGB( 100, 255, 70)Or

Label1.forecolor = VbBlue Setting Height Property

Page 15: visual basic notes

Example:Label1.height = 100

OrCommand1.height = 200

Setting the tooltiptext propertyExample:

Text1.tooltiptext = “This is a text box”

Setting the text propertyExample:

Text1.text = “Amit sharma”

Setting the visible propertyExample:

Label1.visible = trueOr

Text1.visible = false

Setting the width propertyExample:

Text1.width = 250Or

Command1.width = 100

Setting the style propertyExample:

Command1.style = 0Or

Option1.style = 1

Setting the picture propertyExample:

Check1.picture = loadpicture ( “c:\abc.gif”)Or

Command1.picture = loadpicture ( “c:\abc.gif”)Or

Option1.picture = loadpicture ( “c:\abc.gif”)Or

Picture1.picture = loadpicture ( “c:\abc.gif”)

Setting the disabledpicture and downpicture propertyExample:Command1.disabledpicture = loadpicture(“c:\abc.gif”)OrCommand1.downpicture = loadpicture(“c:\abc.gif”)

Page 16: visual basic notes

Setting the value property of checkboxExample:

Check1.value = 0Or

Check1.value = 1

Setting the value property of option buttonExample:

Option1.value = trueOr

Option1.value = false

Setting the stretch property of image controlExample

Image1.stretch = trueOr

Image1.stretch = false

Setting the max/min property of Hscrollbar / VscrollbarExample

Hscroll1.max = 100

Hscroll1.min = 1

Vscroll1.max = 100

Vscroll1.min = 1 Setting the fillstyle and fillcolor property

Example:Shape1.fillstyle = 0

Shape1.fillcolor = RGB(100, 150, 200) Setting the Shape Property of Shape control

Example:Shape1.shape = 1

OrShape1.shape = 3

Setting the windowstate property of formExample:

Form1.windowstate = 0Or

Form1.windowstate = 1

Some Examples:Example1:- Loading a picture in the picture box at run time.

Page 17: visual basic notes

Picture Box

Command Button (cmdload)

Private sub cmdload_click()Picture1.picture = loadpicture (“c:\abc.gif”)

End sub

Example2: – Loading a picture in the image control at run time.

Image control(image1)Command Button( cmdload )

Private sub cmdload_click()Image1.picture = loadpicture (“c:\abc.gif”)

End sub

Example3: List Box

ListBox (list1)

Load

Add

Delete

Clear

Listcount

Listindex

Display

Enter Your Name

Page 18: visual basic notes

Private sub cmdadd_click()List1.additem text1.text

End sub

Private sub cmddel_click()List1.removeitem list1.listindex

End sub

Private sub cmdclear_click()List1.clear

End sub

Private sub cmdcount_click()Msgbox List1.listcount

End sub

Private sub cmdindex_click()Msgbox list1.listindex

End sub

Private sub cmddisp_click()Msgbox list1.text

End sub Adding an item in the list box

List1.additem “Ravi”List1.additem text1.text

Removing an item from the list boxList1.removeitem 0List1.removeitem list1.listindex

Example 4: Hscrollbar / Vscrollbar application

Hscroll1

Page 19: visual basic notes

Command Button (cmdsum) vscroll1

Private sub hscroll1_change()Text1.text = hscroll1.value

End sub

Private sub Vscroll1_change()Text2.text = vscroll1.value

End sub

Private sub cmdsum_click( )Dim a as integer, b as integera = val (text1.text)b = val (text2.text)text3.text = a + b

End sub

Example 5 : Shape Control ApplicationShape Control (shape1)

Sum

Page 20: visual basic notes

Private sub cmdrect_click( )Shape1.shape = 0

End sub

Private sub cmdsquare_click( )Shape1.shape = 1

End sub

Private sub cmdoval_click( )Shape1.shape = 2

End sub

Private sub cmdcircle_click( )Shape1.shape = 3

End sub

Private sub cmdroundrect_click( )Shape1.shape = 4

End sub

Private sub cmdroundsquare_click( )Shape1.shape = 5

End sub

Example 6 : Drive, Directory and file list box Drive1 directory1 file1

Rectangle Square Oval

Circle Rounded Rectangle

Rounded square

Page 21: visual basic notes

Private sub drive1_change( )Dir1.path = drive1.drive

End sub

Private sub dir1_change( )File1.path = dir1.path

End sub

Private sub text1_change( )File1.pattern = text1.text

End sub

Example 7: Timer application. Label1

Timer1 cmdreset

Set the following properties:Timer1.interval = 1000Label1 - > font = MS sans serif, bold, 18

C:

C:\ Program Files ………. ………. ……….

Abc.dllRmn.dllPqr.exe………………………

Enter the pattern

Reset

Page 22: visual basic notes

Dim I as integerPrivate sub cmdreset_click( )

I = 0End sub Private sub timer1_timer ( )

Label1.caption = iI = I + 1

End sub

Example 7: Option Button Application.

lblgrade cmdgrade

Private sub cmdgrade_click( )If optone.value = true then

Lblgrade.caption = “ The grade is A”Else if opttwo.value = true then

Lblgrade.caption = “ The grade is B”Else if optthree.value = true then

Lblgrade.caption = “ The grade is C”Else if optfour.value = true then

Lblgrade.caption = “ The grade is D”End if

End sub

Private sub form_load( )Optone.value = falseOpttwo.value = false

90

70

80

60

Click

Percentage

Page 23: visual basic notes

Optthree.value = falseOptfour.value = false

End sub

Manipulating forms

Setting the startup form

To change the startup form1. Goto project menu - > project peoperties2. Select General Tab3. In startup object listbox select the form4. Click Ok

Loading and unloading the forms

Load form1Unload form1Unload me

Showing and Hiding forms

Form1.showForm2.showForm1.hideMe.hide

Assigning the Access keyCommand buttons can be used by clicking on them or by pressing the alt + <

access key >. To assign a keyboard access key to command button place ampersand( &) in front of the letter that is to be used as access key, while setting the caption property of the command button.

Control Structures in VB

Control Flow:

Page 24: visual basic notes

1. Sequence2. Selection3. Iteration

The if statement:Syntax:

if (condition) thenstatements

end if

Example:

If (a>10) thenPrint ”Raj”

End if

The if…. Then… else statementSyntax:

If (condition) thenstatements

elsestatements

End ifExample: Text1

cmdresult

Private sub cmdresult_click( )Dim m as integerm = val (text1.text)if (m >= 40) then

print ”you are passed”else

print ”you are failed”end if

End sub

Enter the marks

Result

Page 25: visual basic notes

If …then… else if statementSyntax:

If (condition) thenstatements

else if (condition) thenstatements

else if (condition) thenstatements

.

.

.else

statementsEnd if

Example:

Text1

cmdprintday

Private sub cmdprintday_click( )Dim x as integerX = val(text1.text)If(x = 1) then

Msgbox ”Sunday”else if (x = 2) then

Msgbox ”Monday”else if (x = 3) then

Msgbox ”Tuesday”else if (x = 4) then

Msgbox ”Wednesday”else if( x = 5) then

Msgbox ”Thursday”else if (x = 6) then

Enter a number

Print day

Page 26: visual basic notes

Msgbox ”Friday”else if (x = 7) then

Msgbox ”Saturday”Else

Msgbox ”Invalid choice”End if

End sub

Nested ifsExample:

If ( x > 7) thenIf( y <= 8) then

Print ”Ravi”Else

Print ”Amit”End if

ElseIf (P <> 71) then

Print ”vishvas”Else

Print ”Raj”End if

End if

Compound if:Example:If ( x > 7 AND y <> 75) then

Print ”Vicky”Else

Print ”Raj”End if

Example:If( x >= 91 OR p <> 83) then

Print ”Rishabh”Else

Print ”Amrita”End if

The iif( ) function:Syntax:

iif(condition, value1, value2)Example:

Dim num1 as integer, num2 as integer, big as integer

Page 27: visual basic notes

Num1 = 7Num2 = 81Big = iif (num1 >= num2, num1, num2)

Select case statement: If Select case 1. if x = 1 case12. if x > 7 case is > 73. if x < 7 case is < 74. if x >= 7 AND x <= 20 case 7 to 20

Example 1: Text1

cmdprintday

Private sub cmdprintday_click( )dim m as integerm = val( text1.text )select case m

case 1: Msgbox ”Sunday”case 2

Msgbox ”Monday”case 3

Msgbox ”Tuesday”case 4: Msgbox ”Wednesday”case 5: Msgbox ”Thursday”case 6: Msgbox”Friday”case 7: Msgbox”Saturday”case else

Msgbox ”Invalid choice”End select

End sub

Enter a number

Print day

Page 28: visual basic notes

Example 2: Text1

cmdresult

Private sub cmdresult_click( )Dim m as integerM = val( text1.text )Select case m

Case is < 50Msgbox ”Fail”

Case is < 60: Msgbox ”Grade B”

Case is < 75: Msgbox ”Grade A”

Case else: Msgbox ”Grade A+”End select

End sub

Example 3:txtmonth

cmdnod

Private sub cmdnod_click( )Dim n as integer

Enter the marks

Result

Enter the month no.

No. of days

Page 29: visual basic notes

n = val ( txtmonth.text )select case n

case 1,3,5,7,8,10,12Msgbox ”31 days in the month”

case 2Msgbox ”28 days in the month”

Case 4,6,9,11Msgbox ”30 days in the month”

End selectEnd sub

Looping Structures:1. For…Next2. Do loop

(a) Do while…loop(b) Do…loop while(c ) Do until…loop(d) Do…loop until

3. while…wend

1. For…next Example:

For i = 1 to 10 step 1Print “Raj”

Next iExample:

For i = 7 to 22 step 2Print “abc”

Next i

Example:For x = 17 to 1 step -3

Print “raj” Next x

2.(a) Do while…loopExample:

x = 1Do while (x < = 10)

Print “xyz”x = x + 1

loop

Page 30: visual basic notes

Example:x = 10Do while (x > = 1)

Print “xyz”x = x - 1

loop

Example:x = 1Do while (x < = 20)

Print “raj”x = x + 2

loop

2.(b) Do…loop whileExample:

x = 1do

print “ABC”x = x + 1

loop while (x <= 10)Example:

x = 10do

print “raj”x = x - 1

loop while (x >= 1)

2.(c) Do until…loop

While Untilx < 10 x >= 10x <= 10 x > 10x > 1 x <= 1x >= 1 x < 1x < >1 x = 1x = 1 x <> 1

Example:x = 1do until x > 10

print “Raj”x = x + 1

loopExample:

x = 10

Page 31: visual basic notes

do until x < 1print “Raj”x = x - 1

loop

2.(d) Do…loop until

Example:x = 1do

print “Raj”x = x + 1

loop until > 10

Example:x = 10do

print “Raj”x = x - 1

loop until x < 13. While wend

Example:x = 1while x <= 10

print “raj”x = x + 1

wend

Example:x = 10while x >= 1

print “raj”x = x - 1

wend

Nested loopsExample:

Page 32: visual basic notes

for I = 1 to 3 step 1for j = 1 to 5 step 1

print "raj"next j

next iExample:

i=1do while i<=3

j = 1do while j<=5

print "raj"j=j+1

loopi=i+1

loop

Exiting from loops Exit For Exit DoExample: (Exit For) for i=1 to 10 step 1

if (I = 7) then Exit for

End if print i next i

Example: (Exit do) x=1

do while x<=10 if(x=7) then

Exit doEnd ifprint xx=x+1

loop Arrays

Array is a collection of variables of same type that are referenced by a common name.

Example: Private sub Command1_Click()

dim a(4) as integerdim i as integerfor i=0 to 4 step 1

a(i) = inputbox "enter a number "next i

for i=0 to 4 step 1

Page 33: visual basic notes

print a(i)next i

End Sub

dim x(1 to 5) as integerdim x(5 to 9) as integer

Redim statementExample: Private sub Cmdprint_Click( )

dim a( ) as integerdim i as integerredim a(4)for i=0 to 4 step 1

a(i) = inputbox "Enter a number"next ifor i=0 to 4 step 1

print a(i)next iredim a(9)print "array after re-dimensioning "for i=0 to 9 step 1

print a(i)next i

End sub Preserve statement

Redim preserve a(9)

Procedures & Functions

Types of Procedures

1. Sub Procedures2. Function Procedures3. Property Procedures

1. Sub Procedures: A sub procedure or subroutine or sub is a procedure that performs a specific task but does not return a value.

Example: Procedure without arguments

Page 34: visual basic notes

cmdprintmessagePrivate sub cmdprintmessage_click( ) print "Raj" print "Daljeet" disp or call disp print “ravi” print "kailash" call disp print "vishal"End subPrivate sub disp( ) print "Harish" print "Manish" print "Vicky"End sub

Example: Procedures with arguments

text 1

text 2

text 3

cmdsumPrivate sub cmdsum_click( )

dim x as integer, y as integerx = val (text1.text)y = val(text2.text)call findsum (x, y) or findsum x, yfindsum x …. Errorfindsum x, 5, y …. Error

End subPrivate sub findsum (n as integer, m as integer)

text3.text = n + mEnd sub

2. Function Procedures: A function is a procedure that performs a specific task and returns a value.

Types of Functions

Print message

Enter a number

Enter second number

Result is

sum

Page 35: visual basic notes

1. User Defined Functions2. Built in Functions or Library Functions

Example:

Text1

Text2

Text3

cmdsum

Private sub cmdsum_click( )dim x as integer, y as integer, z as integerx = val(text1.text)y = val(text 2.text)z = findsum(x, y)text3.text = z

End subPrivate function findsum (n as integer, m as integer) as integer

findsum = n + mEnd function

Passing Parameters to Procedures1. Call by Value (pass by value) ……………….Byval2. Call by Reference (pass by reference) ..……ByrefExample:

cmdprint

Private sub cmdprint_click( )dim x as integer x=5print x …. 5call change(x) or change x …. 100print x …. 100

End subPrivate sub change (Byref n as integer)

n=100

Print

Enter a number

Enter a second number

Result is

Sum

Page 36: visual basic notes

print nEnd sub

Using Optional Arguments

Text1

Text2

Text3

cmdsum

Private sub cmdsum_click( )dim x as integer, y as integerx = val(text 1.text)y = val(text 2.text)findsum x, yfindsum xfindsumfindsum 2, y, 5 …. error

End subPrivate sub findsum (optional n as integer = 70, optional m as integer = 80)

text3.text = n + mEnd sub

Exiting from Procedures1. Exit Sub2. Exit Function

text1

cmdcheck

Private sub cmdcheck_click( )dim x as integer x = val(text1.text)call samplepro(x)

End subPrivate sub samplepro (n as integer )

if (n > 50) thenmsgbox "you have got a car"

else

Enter first number

Enter second number

Result is

sum

Enter a no.

check

Page 37: visual basic notes

Exit subEnd if

End sub

Library Functions String Functions:

1. Lcase and Ucase FunctionsPrint Ucase(“hello”) - HELLOPrint Lcase (“HELLO”) - helloText1.text = Ucase(text1.text)Text1.text = Lcase(text1.text)

2. Len Functiondim x as integerx = len(“raj”)print x - 3x = len(text1.text)print xprint len(“Rajeev”) - 6

3. Trim, Ltrim, and Rtrim functionsText1.text = Ltrim(“ daljeet”)Text1.text = Rtrim(“sandeep ”)Text1.text = trim(“ amit arora ”)Text1.text = trim(text1.text)Text1.text = rtrim(text1.text)

4. Left and Right functionsdim n as string, m as stringm = “daljeet”n = right(m, 4)print n - jeetm = “raj arora”print left (m,3) - raj

5. Mid functiondim x as string, y as stringx = “raj kumar arora”y = mid (x, 5, 5)print y - kumar print (x,11, 5) - arora

6. Instr functiondim searchstring as string, searchchar as string, mypossearchstring = “XXpXXpXXPXXP”searchchar = “P”mypos = instr (4, searchstring, searchchar, 1) - 6

Page 38: visual basic notes

mypos = instr(1, searchstring, searchchar, 0) - 9mypos = instr(searchstring, searchchar) - 9mypos = instr(searchstring, ”w”) - (0) not found

7. Space Functiondim p as stringp = “raj” & space(10) & ”puri”

print p - raj puri

8. String Functiondim x as string x = string(10, ”a”)print x - “aaaaaaaaaa”x = string (5, ”ABC”)print x - “AAAAA”

9. Str Functiondim x as string, y as stringx = str(1205) - “1205”y = str(1305) - “1305”print 12 + 15 - 27print str(12) + str(15) - 1215print “12” + “15” - 1215

10.Asc Functiondim x as integerx = asc(“A”)print x - 65print asc(“Abc”) - 65x = asc(“a”)print x - 97ASCII ValuesAmerican Standard Codes For Information Interchange.“A” to “Z” - 65 to 90“a” to ”z” - 97 to 122“0” to “9” - 48 to 57

11.Chr Functiondim x as stringx = chr(65)print x - Aprint chr(66) - B

x = chr(98)print x - b

12.Strreverse FunctionDim x as stringx = “Neeraj“

Page 39: visual basic notes

Print strreverse(x) - jareeNPrint strreverse (“neeraj”) - jareenText1.text = strreverse(text1.text)

Numeric Functions1. Int & Fix Functions

print int(14.1) …. 14print int(14.6) …. 14print int(-14.1) …. –15print int(-14.6) …. –15

print cint(14.1) …. 14print cint(14.6) …. 15print cint(-14.1) …. –14print cint(-14.6) …. –15

print fix(14.1) …. 14print fix(14.6) …. 14print fix(-14.1) …. –14print fix(-14.6) …. –14

2. Sgn Functionif number is Sgn function returnsgreater than 0 1equal to 0 0less than 0 -1

print sgn(-5) …. -1print sgn(0) …. 0print sgn(10) …. 1x = sgn (-5)print x …. -1

3. Val( ) Functionprint 2+5 …. 7print “2” + ”5” …. 25print val(“2”) + val(“5”) …. 7 print val(“18th Road”) …. 18

4. Rnd FunctionText1.text = rnd(1)

Or print rnd(3)To produce a random number within the given range.int ((upperbound – lowerbound + 1) * rnd + lowerbound)

Example:(To produce a random number between 1 and 6)dim x as integer

Page 40: visual basic notes

x = int ((6 – 1 + 1) * rnd + 1)Or x = int (( 6 * rnd) + 1)

Date and Time Functions1. Now( ) Function

print now( )Or print now .… 1/17/06 11:25:50 AM

2. Date and Date$ FunctionsPrint date …. 1/17/04Print date$ …. 01-17-2004

Date Date$- Variant String- Uses ”/” Uses “-“- Do not places 0 Places 0- Do not appends 19 or 20 Appends 19 or 20

before year before year

3. Time and Time$ FunctionsPrint time …. 9:11:50 PMPrint time$ …. 21:11:50

Time Time$- Variant String- 12 hour 24 hour4. Datepart FunctionSyntax:

Datepart (interval, validdate)Intervalyyyy yearq quarterm monthy day of the yeard dayw weekdayww weekh hourn minutes second

Example:dim x as datex = #1/17/2006#Print datepart (“m”, x) - 1Print datepart(“yyyy”, now) - 2006

5. Day, Month and Year Functions

Page 41: visual basic notes

Print day(date) - 17Print month (date) - 1Print year(date) - 2006dim x as datex = #1/19/2006#print year(x) - 2006 print day(x) - 19

6. Hour, Minute and Second Functionsdim x as datex = #12:10:41 AM#Print hour(x) - 12Print minute(x) - 10Print second(x) - 41Print minute(now)

7. Timer( ) FunctionPrint timer

Or Text1.text = timer( )

8. Dateadd and Datediff FunctionsSyntax:

Dateadd (interval, number, olddate)Example:

x = dateadd(“y”, 25, now)Or x = dateadd(“yyyy”, 3, now)

Datediff FunctionSyntax: Datediff(interval, date1, date2)Example:

x = #1/17/2006#y = #2/25/2004#n = datediff (“yyyy”, x, y)print n …. 2

Miscellaneous Functions1. Isdate( ) Function

dim x as integer, y as stringx = 10y = “12/17/2005”print isdate(x) .… falseprint isdate(y) .… true

2. Isnumeric( ) Functionprint isnumeric(x) …. trueprint isnumeric(y) …. false

Page 42: visual basic notes

3. Isempty( ) Function4. Isnull( ) Function

5. Vartype( ) FunctionExample:

dim x as integer, y as stringPrint vartype (x) …. 2Print vartype (y) …. 8

6. Inputbox( ) FunctionSyntax:

Inputbox (prompt [,title] [,default] [,xpos] [,ypos]…)Example:

p = inputbox(“Enter the number“, “My Project”, 10, 100, 200)

7. Msgbox( ) FunctionSyntax:

Msgbox (prompt [,buttons] [,title])Example:

Msgbox (“A Trial Message“)x = Msgbox (“Do you wish to continue:“, 4 + 32, “My Project”)