introduction on vba lab 05 ins.tahani al_dweesh. lab objectives introduction calculation with vba...

45
In The Name Of Allah Introduction on VBA Lab 05 ins.Tahani Al_dweesh

Upload: lizbeth-bridges

Post on 28-Dec-2015

220 views

Category:

Documents


1 download

TRANSCRIPT

1

In The Name Of AllahIntroduction on VBALab 05

ins.Tahani Al_dweeshLab ObjectivesIntroduction Calculation with VBAStoring and Retrieving Variables in a WorksheetUsing Excel FunctionsChecking for conditionsLoopsObject

ins.Tahani Al_dweeshIntroduction Visual Basic for Applications

Used to customize many Microsoft applications (Excel, Word, Access, Power Point) host applications.ins.Tahani Al_dweeshIntroduction : ContVisual Basic for Applications, Excels:

Powerful built-in programming language , permits you to easily incorporate user-written functions into a spreadsheet.ins.Tahani Al_dweesh4Permits Incorporate Programming LanguagesThree groups:Low-level languages are used to manipulate the computer at a basic level: assembly language.

High-level languages are used to create stand-alone applications: C, C++, Fortran, Java, Visual Basic.

Application level languages are used to manipulate an application program: VBA.

ins.Tahani Al_dweesh5A computer language that deals with hardware registers by name; Visual Basic Editorins.Tahani Al_dweesh

To open VBA Click on Alt+F11

Calculations with VBACreating a simple function

ins.Tahani Al_dweeshThe Steps:1- Open a blank workbook using File | New.2- Select Developer | Visual Basic Editor (Alt+F11)3- Within the VBA editor, select Insert | Module from the menu.

ins.Tahani Al_dweesh

4- Within the newly-created macro module, type the function statement.

ins.Tahani Al_dweeshFunction function_name (arg1,arg2,)Function structure End FunctionExample ins.Tahani Al_dweeshFunction addtwo(x, y)addtwo = x + yEnd Function

5- Return to Excel. In cell A1 enter .

6- Hit , to see the result.

= addtwo(3 ; 5)USE FunctionsThe function you typed it appears in the function wizard, just as if it were a built-in Excel function.

ins.Tahani Al_dweesh

cont

ins.Tahani Al_dweeshTo see this:in the function categoryscroll to and highlight User DefinedNote that Addtwo appears.SubroutineA subroutine (called a sub by VBA) subroutine, which is a set of statements which execute when invoked.

ins.Tahani Al_dweeshSub Subroutine_name()statementEnd SubA Simple Example of a Subroutine:

run the subroutine by using Developer | Macro Or (Alt+F8)ins.Tahani Al_dweeshSub displaybox()MsgBox(Welcome)End SubSubroutine

ins.Tahani Al_dweesh

-then double-clicking on displaybox out of the list.-Or Running.

Create Button to Invoke a SubroutineCreating a Button to Invoke a Subroutine:- creating a button in the spreadsheet is a way to create a shortcut to the subroutine.ins.Tahani Al_dweesh

Create Button to Invoke a SubroutineMove the mouse to the spreadsheet ,hold down the left mouse button, and drag to create a rectangle.dialog box will pop up and one of the choices will be displaybox. Double click on it.

ins.Tahani Al_dweesh

Create Button to Invoke a Subroutine

ins.Tahani Al_dweeshWhen you are click on the button show Message ,the message will be appearsDifferences Between Functions and Subroutines:

SubroutinesFunctionsInvoked by buttonyesnoInsert into cell no yesChange the displayyesnoins.Tahani Al_dweeshObject ModelIncludes such objects as:workbooks, worksheets, cells, rows, columns, ranges, charts and pivot tables

ins.Tahani Al_dweesh20ObjectsAn object:-is something that is identified by its properties (what it is) and methods (what it can do).

For example:-Range is an Excel VBA object and one of its properties is value. -We connect an object to its property by a period (a dot or full stop).

ins.Tahani Al_dweesh Range("A1").Value = 10Using Ranges A Range object represents a cell, a row, a column, a rectangular block of cells, or the union of many rectangular blocks (a non-contiguous range).

ins.Tahani Al_dweeshStoring and Retrieving Variables in a WorksheetThere are three ways to read and write to cells:Range( ) give cells a name,Range( ).Activate lets you easily get at cells by using traditional cell addresses (e.g. A1).Cell( , ) lets you address cells using a row and column numbering scheme.ins.Tahani Al_dweesh1. Range give cells a name-Using a named range to read and write numbers from the spreadsheet:1- created a named range : - to create a named range :

ins.Tahani Al_dweesh

1. Range give cells a nameins.Tahani Al_dweesh2- in the Module

Sub ReadVariable()x = Range(test ).ValueMsgBox (Str(x))End Sub1. Range give cells a name3 -Enter the value 4 in the cell you just named test.

4- run the subroutine by using :Developer |Macro Or (Alt+F8)

ins.Tahani Al_dweesh

ins.Tahani Al_dweesh

The number on cell2. traditional cell addresses-Reading from Cells Which are not Named:1-first have to activate the worksheet containing the cell.

notice that when you have finished calling this function, the cursor has moved to cell A1 in Sheet2ins.Tahani Al_dweeshSub ReadVariable2()Worksheets(Sheet2).ActivateX=Range(A1).ValueMsgBox (Str(x))End Sub2. traditional cell addresses-Writing to Cells Which are not Named:get number of cell (A1) then write this number in cell (B2)

ins.Tahani Al_dweeshSub WriteVariable2()Make Sheet2 the active sheetWorksheets(Sheet2).ActivateMake A1 the active cellX=Range(A1).ValueMake B1 the active cellRange(B1).Value =XEnd SubExample of unnamed range:ins.Tahani Al_dweeshplaces text "AB" in range A1:B5, on Sheet1 Worksheets("Sheet1").Range("A1:B5") = "AB"Another Wayplaces text "AB" in range A1:B5, on Sheet1 Worksheets(Sheet1").ActivateRange ("A1:B5") = AB

ins.Tahani Al_dweesh3.using a row and column numbering scheme-Using the Cells Function to Read and Write to Cells:put number (1) in cell (A3) Then read this number and write it in cell (C3)1-first have to activate the worksheet containing the cell.

ins.Tahani Al_dweeshSub CellsExample() Make Sheet2 the active sheetWorksheets(Sheet2).Activate The first entry is the row, the second is the column Write the number 1 into cell A3Cells (3, 1) = 1 Copy the number from cell A3 into cell C3Cells (3, 3) = Cells (3, 1)End SubChecking for Conditions-To effectively control the VB program flow, we shall use If...Then...Else statement together with the conditional operators and logical operators. -The general format for the if...then...else statement is

If...Then...Else ins.Tahani Al_dweeshExample ins.Tahani Al_dweeshFunction check( x )If x > 0 Then MsgBox (Positive Number")ElseMsgBox (Negative Number")End IfEnd FunctionUse the Function ins.Tahani Al_dweesh

Select Case:

Select Case < Expression to test> Case Do something Case Else Do something else End Selectins.Tahani Al_dweeshSub selectTest()Select Case Range("A1").ValueCase 100 To 400Range("B1").Value = "it's between"Case ElseRange("B1").Value = "it's not between"End SelectEnd SubUse the Case Selectins.Tahani Al_dweesh

LoopsA simple for loop :For....Next Loop The format is:

ins.Tahani Al_dweeshFor counter=start to end (Step increment) One or more VB statements Next

- counter : A numeric variable used as the loop counter.

- start and end : The initial and final values of the counter.

- increment : The amount the counter is changed each time through the loop.

#Notice that increment can be negative

ins.Tahani Al_dweeshExample ins.Tahani Al_dweeshSub for_loop()Dim Sum As IntegerDim I As IntegerSum= 0 i , 0,1,2 For i = 0 To 2Sum = Sum + iNext iMsgBox (Str(Sum))End Sub

ResultLoopsDo While (condition true) LoopRuns while condition is true.

Do ... Loop While (condition true) Runs at least one time, and while the condition is true subsequently.

ins.Tahani Al_dweeshThe formats are:

a) Do While condition Block of one or more VB statements Loop

ins.Tahani Al_dweeshCount= 0 Do while count