You are visitor number

 


Nico's VB  Language Basics

 

 

Introduction to BASIC

Before one can start programming in Visual Basic it is important to become familiar with basics of BASIC

"Beginners Access Symbolic Instruction Code" known as BASIC was developed at Dartmouth College by John Kemmey and Thomas Kurtz in the mid 1960’s

Basic is a computer language whose instructions resemble algebraic formulas, augmented by English words such as GO TO , INPUT , PRINT , IF , THEN ELSE

Because of its similarity to elementary algebra Basic is particularly suited to solving problems in Science , Mathematics ,Engineering and Finance.

Basic programming can be a lot of fun

Structure of a BASIC Program

An example of a simple Basic program to get the radius and calculate the diameter of the circle

 

R = InputBox

A = 3.14159 * R

MsgBox A

End

1.0 Simple Input / And output Message Boxes

MsgBox is used to Place a small Form on the screen Displaying a message and waiting for the user to press an OK Button before the program continues

 

InputBox is used to Place a small Form on the screen Displaying a message (Prompt) and has a text field for the user to type some input . This will also be waiting for the user to press an OK or Cancel Button before the program continues

 

2.0 Mathematical Operators

* Multiplication
/ Division
+ Addition +
/ Subtraction–
^ Raze to the power of

 

 

3.0 Variables

A variable is a name that represents a Number or String or Date

A variable is also the name given to the memory location in the computer that stores this

Number or String or Date

 

Variable Type Description
Integer Stores numbers with no decimals
Long Stores Larger Integers
Single Stores (Floating point) Numbers with decimals (Scientific format)
Double Stores Larger Singles
Byte An 8 Bit number 0 to 255 or a character
Boolean A Yes /No type variable stores "True" or "False"
Currency Stores Numbers with Decimals
String Stores text
Date Stores date and time values
Variant This is a variable that can hold any of the above

However this take up a large amount of memory

Object This is used to make an instance of a class (OOP)

 

3.1Variable Declaration

Implicit Declaration

By default you don’t need to declare variables before you use them

However by default they become of the Variant Type

If you don’t want that then you need to declare them using the Dim statement

Dim MyVar as Integer

Dim MyVar as string

Dim Name as string

 

Explicit Declaration

If you use the following statement you are forced to declare all variables before using them

Option Explicit

3.2 Naming Variables

When declaring variables observe the following rules

  1. You must Start with a letter
  2. You can mix letters and numbers
  3. Use variable names that are meaningful (Someone else will one day be debugging your code)

Different programmers have different styles in declaring Variable names

Dim Y2K as integer

Dim My_Var as integer

Dim MyVar as integer

Dim nMyVar as integer ‘Hungarian Naming Convention

Today most of the Guru’s are switching to using Hungarian Variable names

Refer to the Hungarian Naming Convention Chart

4.0 Array Variables

Arrays are variables that can simultaneously hold more that one value to text string.

Declaring Arrays

Dim MemberNames(24) as string ‘ This will alloy you to save 25 names or strings in this array

Dim Results(33) as integer ‘ This will alloy you to store 34 numbers in this array

 

Array Index’s

If you wish to store the 15th name in the above array you need to specify the specific array element to save the data this is how its done

MembersNames(14)="Nick Michael"

And if you wish to recall the 19th name this is how you access the specific array element

MsgBox MembersNames(18)

Array Indexes always start with 0 unless

 

The Upper And Lower Bounds of the Array

Ubound returns the highest valid index value

Lbound Returns the lowest valid index value (Option Base can change this)

 

4.1 Dynamic Arrays

Sometimes you don’t know how large to make the array

Or you want to free the memory when you don’t need it

Then you would declare your arrays as Dynamic Arrays

 

Declaring Dynamic Arrays

You declare the array with no value between the brackets

Dim MyArry( ) as Integer

 

Setting the Size or Resizing of the Dynamic Array in real time

ReDim MyArry(20)

ReDim MyArray(30)

ReDim MyArray(0)

ReDim MyArray(100 + Ubound( MyArry( ) ) add another 100 elements to the array

The problem with doing that is you loose all the data in the array if you need that use the Preserve option

ReDim Preserve MyArray(45) this will keel all elements whose index is smaller than 45

 

Freeing up the Memory used by your array

Erase MyArry

 

5.0 Mathematical Functions

 

Sqr Square Root
Log(n) Natural Log ( log base e)
Log10(n) Log10(n) (log base 10) = Log(n) / Log(10)
   
   
Exp Returns exponent of e (e=2.718282.)

Const e = 2.718281828459

Abs Returns a Positive value for an expression or variable
Sgn Returns the sign

For Greater than zero returns 1

For Equal to zero returns 0

For Less than zero returns -1

Int Returns an integer (no decimals)

 

6.0 Trigonometric functions

 

 

The problem with Basic and even VB is that  Angles are passed to Trig functions in Radians

"All trigonometric functions are calculated from angles expressed in Radians"

In order to work with angles in degrees you need to define Pi and or Rad

Const Pi = 3.14159265359

or

Pi = 4 * Atn(1) ‘ This is an approximation for the value of Pi (not so accurate)

180 degrees=Pi Radians

1 Degree=Pi/180 Radians

1 Degree=3.14/180=0.017Radians

1 Degree=1.7E2 Scientific format (Single) 

Const Rad = 1.74532925199433E-02 (double) This is the most accurate representation to use for VB

If you multiply the angle in degrees by Rad you will convert it to radians and can use the trigonometric

Functions e.g. Sin of x(degrees)=Sin(x * Rad) but don’t forget to define Rad

Sin(x) Sine of x(radians)
Sin x in Degrees Sine of x(degrees)=Sin(x * Rad)
Cos Cosine of x(radians)
Tan Tanjent of x(radians)
Atn Inverse Tangent (arc tan)
ArcSin has to be calculated  
ArcCos has to be calculated  

 

 

For Other Functions Refer to Function Charts on this webPage

 

 

7.0 Declaring Procedures

There two types of Procedures:

  1. Subs (Subroutines)
  2. Functions

 

7.1 Subs (Subroutines)

Subs are called and no values are returned

However they can take values passed to them in the form of Parameters

Declaring a Sub

Sub MySub

End Sub

Declaring a Sub with Parameters

Sub MySub(Param1 as integer, Param2 as string)

End Sub

Calling a Sub

MySub or

Call MySub( ) or

MySub 123,"John Doe" or

Call MySub(123,"John Doe") or

If you use the Call command you must add the Parenthesis ( ) to your subroutine

Optional Parameters

Sometimes you may want to use default parameter values but allow for overriding these values

Sub MyFunct(optional Param1 as integer, optional Param2 as string)

End Sub

Testing if an Optional parameter has a value passed to the Sub (IsMissing)

If not Ismissing( Param1) then Statement1  

7.2 Functions

Functions are procedures that return a value or a string

They can also take values passed to them in the form of Parameters

Declaring a Function

Function MyFunct as integer

End Function

Declaring a Function with Parameters

Function MyFunct(Param1 as integer, Param2 as string) as integer

End Function

Calling a Function

MyVar=MyFunct or

MyVar=MyFunct 123,"John Doe" or

MyVar=MyFunct(123,"John Doe")

Declaring Variables within a Function or Sub Local Variables

This is done the same way as above

However:

  1. This variable is only accessible within the Procedure (Procedural Scope)
  2. This variable is discarded/destroyed as soon as the Procedure ends (Variable Life)
  3. If the variable is declared as a static variable it will not be destroyed after the Procedure ends

Optional Parameters

Sometimes you may want to use default parameter values but allow for overriding these values

Function MyFunct(optional Param1 as integer, optional Param2 as string) as integer

End Function

Testing if an Optional parameter has a value passed to the function (IsMissing)

If not Ismissing( Param1) then Statement1

Passing Arguments By reference or By value

Function MyFunct(ByRef Param1 as integer, ByRef Param2 as string) as integer

End Function 

Function MyFunct(ByVal Param1 as integer, ByVal Param2 as string) as integer

End Function 

8.0 Flow Control

8.1 If Statement

IF ELSE END IF

A simple English like statement to switch flow between one ore two statements

If     Name="John" then

        Statement1

Else

    Statement2

Endif

 

ELSE IF

This is an English like statement you can use (to follow an IF ELSE ENDIF statement) to optionally switch to another statement with a condition test (Name="Nick")

Else If Name = "Nick" then Statement3 

8.2 Case Statement

SELECT CASE CASE END SELECT

A simple English like statement to switch flow to one of many statements

 

Select Case MembersName

        Case "Fred"

                            Statement1

        Case "John"

                            Statement2

        Case Else

Statement 3

End Select 

8.3 For Next Loop

FOR NEXT

A simple English like statement to force a block of code to be repeated a fixed number of times

For I= 1 to 10 Step 5

            Statement1

Next I

This is the most versatile loop technique as you can specify the lower the upper bount and the increment size (positive or negative)

 

8.4 Do While Loop

DO WHILE

A simple English like statement to force a block of code to be repeated until a test condition is met

Do

        Statement1

While I<5

8.5 Do Until Loop

DO UNTIL LOOP

A simple English like statement to force a block of code to be repeated until a test condition is met

Do Until I=10

    Statement1

Loop

8.6 While Loop

WHILE WEND

A simple English like statement to force a block of code to be repeated until a test condition is met

While I <5

    Statement1

Wend

8.7 For All

FOR ALL END FORALL

A simple English like statement to force a PROCESS to be repeated FOR ALL valid conditions of l a test condition

 

 

9.0 Practical Examples

Now Lets use some of the mathematical operators and functions in examples

1) Calculate the hypotenuse of a triangle with adjacent sides 35 and 65

A=35

B=65

H=Sqr (A*A + B*B)

Msgbox H

2) Calculate the fuel consumption in Litres per 100Km for a car using 53litres to do 450Km

F=53

D=450

R=(F/D) * 100

Msgbox R & "Litres per 100KM"

3) If 1 litre of fluid costs $5.3 and you need 4.5 liters per day how much will it cost you in a leap year

C=5.3

DR=4.5

YR=4.5*366

TOTAL=YR*C

Msgbox TOTAL

4) Your store has 53 soap bars The economic order quantity is 200 and the cost per bar at that level is

$0.2 If you sell 8 bars per day at $0.22 What is the Resale value of your stock if February

after buying stock on the 3rd January .How much profit did you make

PurchPrice=0.2

ResalePrice=0.22

CurStock=53

OrderQty=200

TotalStock = CurStock+ OrderQty

DailySales=8

JanuarySales=31* DailySales

FinalStock= TotalStock - JanuarySales

ResaleValue= FinalStock * ResalePrice

Msgbox ResaleValue

UnitProfit= ResalePrice – PurchPrice

TotalProfit= UnitProfit * JanuarySales

Msgbox TotalProfit

5) If you pay cash for a Television Set you get a 33% discount on the amount of $120.

If you borrow the money from the bank and pay it off in one year at 7.5% Simple Intrest

What did the TV cost you

Price=120

Disc=33

Disc=Disc/100

Payment=Price-Disc

Intrest=7.5

Intrest=Intrest/100

Cost=Payment + (Intrest*Payment)

Msgbox "$" & Cost

 

6) If it costs $133 to advertise on radio and 51000 listeners will be targeted

And itcosts $3500 to advertise on TV and 2 000 000 listeners will be targeted

And it costs $350 to advertise in the newspaper and 170000 readers will be targeted

Which is the most cost effective medium to advertise in

RadCost=133

RadTarget=51000

RadioPerPerson=RadCost / RadTarget

TvCost=3500

TvTarget=2000000

=TvCost/TvTarget

NewsPCost=350

NewsPTarget=170000

NewsPPerPerson= NewsPCost / NewsPTarget

If NewsPPerPerson < TvPerPerson and NewsPPerPerson < RadioPerPerson then _

Msgbox "News Papper is the most cost effective medium to advertise in"

If TvPerPerson< NewsPPerPerson and TvPerPerson< RadioPerPerson then _

Msgbox "Television is the most cost effective medium to advertise in"

If RadioPerPerson < NewsPPerPerson and RadioPerPerson < TvPerPerson then _

Msgbox "Radio is the most cost effective medium to advertise in"

 7) If 1.8 times the temperature in Celcius + 32 is the temperature in Farenheit

And the temperature is 105 deg F what is that in celcius

F=105

C=(F-32)/1.8

Msgbox C & "deg C"

8) Calculate the sensitivity of a Radio Receiver in dBm if 5 Micro volts (V=5E-6) are used to reach the

required threshold for 12dB SINAD. Given the impedance as 50 Ohm.

Power = (V*V) / 50

Dbm=10 * Logbase10 (Power/1000)

Solution :

V=5E-6

P=(V*V)/50

Level=10*( Log(P/1000) / Log(10) )

Msgbox Level & "dBm"

9)      A German tourist in South Africa Has 6500Dm in DM Traveller’s Cheques

And the Exchange rate for DM is $0.43= 1DM and exchange rate for Dollars is R6.2=$1.00

If he converts his DM to R How many Rand does he get if he converts all his travellers cheques

DM=6500

DmRate=0.43 ‘ USD

USDrate= 6.2

ZAR=DM*USDrate*DmRate

Msgbox "R" & ZAR

10) The following series of numbers is known as the Fibonacci Number series

1 1 2 3 5 8 13 21 34

write a program to generate this series

A=0

B=1

F=0

Msgbox A

Msgbox B

for I=1 to 7

F=A+B

A=B

B=F

MsgBox B

next I

11) Use Dynamic variables to create a Phone Book Aplication that holds Names and Phone Numbers

Dim sName() as String ‘Dynamic Array

Dim sPhone() As String ‘Dynamic Array

Dim bQuit as Boolean

Dim sTemp as String

bQuit= "False"

Do

I=InputBox "0 to Quit 1 to add a number 2 to recall a number"

 

Select Case I

Case 0

bQuit="True"

Case 1

Redim Preserve sName ( Ubound(sName) +1 )

Redim Preserve sPhone( Ubound(sPhone) +1 )

sName ( Ubound(sName) ) = InputBox "Enter Name "

sPhone( Ubound(sPhone) ) = InputBox "Enter Phone Number

Case 2

sTemp=InputBox "Enter Name to search for"

For J=0 to Ubound(sName)

If sName(J)=sTemp then

MsgBox sName(J) & " " & sPhone(J)

End If

Next J

End Select

While bQuit="False"

 

 

Top Of Page


WB01339_.gif (896 bytes)Return to Nico's Visual Basic Page

       

Please send mail to: Nicom@rocketmail.com  with questions or comments about the content  this VB Web site.


This page hosted by Get your own Free Home Page

1