Visual Basic Objects / Properties / Methods PropertyAdjective ObjectNoun Part of the application Attribute MethodVerb Action to do something.

Slides:



Advertisements
Similar presentations
CSI 1306 PROGRAMMING IN VISUAL BASIC PART 2. Part 2  1. Strings  2. Translating Conditional Branch Instructions  3. Translation Set 2  4. Debugging.
Advertisements

Object Oriented Programming A programming concept which views programs as objects with properties and ways to manipulate the object and the properties.
Visual Basic for Applications. What it does Extends the features and built in functions of Excel – Create and run VB procedures – Some may be easy to.
Tutorial 8: Developing an Excel Application
Some computer fundamentals and jargon Memory: Basic element is a bit – value = 0 or 1 Collection of “n” bits is a “byte” Collection of several bytes is.
AE6382 VBA - Excel l VBA is Visual Basic for Applications l The goal is to demonstrate how VBA can be used to leverage the power of Excel u VBA syntax.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Tutorial 12: Enhancing Excel with Visual Basic for Applications
Slide 1 VB Program Flow Control. Slide 2 Making Decisions v Decision Statement: control the execution of parts of the program based on conditions. v The.
Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure.
VBA Programming Session #2. Things to Review  Variables  Procedures: Subs & Functions  If…Then  For…Next.
Chapter 4 Making Decisions
Adding Automated Functionality to Office Applications.
VBA & Excel Barry L. Nelson IEMS 465 Fall Quarter 2003.
Exploring Microsoft Excel 2002 Chapter 8 Chapter 8 Automating Repetitive Tasks: Macros and Visual Basic for Applications By Robert T. Grauer Maryann Barber.
Chapter 5 new The Do…Loop Statement
 Excel – Basic Elements  Using Macros  Excel VBA Basics  Excel VBA Advanced.
IE 212: Computational Methods for Industrial Engineering
Saeed Ghanbartehrani Summer 2015 Lecture Notes #4: Working with Variables and User Interfaces IE 212: Computational Methods for Industrial Engineering.
VBA for Excel. What is a spreadsheet? u An Excel spreadsheet is a set of worksheets  Each worksheets is made up of rows and columns of cells  Rows are.
Introduction on VBA Lab 05 ins.Tahani Al_dweesh. Lab Objectives Introduction Calculation with VBA Storing and Retrieving Variables in a Worksheet Using.
1 Visual Basic for Applications (VBA) for Excel Prof. Yitzchak Rosenthal.
University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA 1 Lecture Outline Record macro and examine VBA code VBA Editor (IDE)
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Chapter 17: Arrays Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Copyright © 2008 Pearson Prentice Hall. All rights reserved. 1 Microsoft Office Excel Copyright © 2008 Pearson Prentice Hall. All rights reserved
Class 3 Programming in Visual Basic. Class Objectives Learn about input/output Learn about strings Learn about subroutines Learn about arrays Learn about.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Lecture Set 5 Control Structures Part A - Decisions Structures.
Visual Basic for Applications Macro Programming For Microsoft Office.
VBA Lab 2 I ns.Samia Al-blwi. Visual Basic Grammar Object: Visual Basic is an object-oriented language. This means that all the items in Excel are thought.
Working with the VB IDE. Running a Program u Clicking the”start” tool begins the program u The “break” tool pauses a program in mid-execution u The “end”
CS285 Visual Basic 2 Department of Computing UniS 1 Statements in Visual Basic A statement is the fundamental syntactical element of a program smallest.
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
Lab 4 Range Review, Control Logic and Loops ► Range Review ► Control Logic and Loops ► Exercise.
Chapter 9 Macros And Visual Basic For Applications.
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
1 CS105 Discussion 5 – Variables and If Announcements MP 1 due on Monday Midterm 1 on Tuesday If you need a conflict, request it NOW!!
ME 142 Engineering Computation I Using Subroutines Effectively.
Lab 6 (2) Arrays ► Lab 5 (1) Exercise Review ► Array Concept ► Why Arrays? ► Array Declaration ► An Example of Array ► Exercise.
Copyright © 2001 by Wiley. All rights reserved. Chapter 6: Using Arrays Control Arrays List Arrays Finding Items in Arrays Multiple Forms 2-Dimensional.
1 Scripting Languages VBScript - Recognized mainly by Internet Explorer only - Netscape does have a plug-in JavaScript - Recognized by Internet Explorer.
Introduction to Excel VBA UNC Charlotte CPE/PDH Series December 17, 2009.
Chapter Making Decisions 4. Relational Operators 4.1.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Visual Basic Programming I 56:150 Information System Design.
Chapter 6 Looping Structures. Do…LoopDo…Loop Statement Can operate statements repetitively Do intx=intx + 1 Loop While intx < 10 –The Loop While operates.
VBA Navigation, Conditionals, and Boxes. VBA Navigation.
Chapter 4 Getting Started with VBA. Subroutines Subroutine is the logical section of code that performs a particular task. Subroutine is also called a.
© 2006 Lawrenceville Press Slide 1 Chapter 6 The Post-Test Do…Loop Statement  Loop structure that executes a set of statements as long as a condition.
Controlling Program Flow with Looping Structures
5.1 Introduction Problem Solving –Requires understanding of: Building blocks Program-construction principles BZUPAGES.COM.
Lab 6 (1) Range Review, Control Logic and Loops ► Control Logic and Loops ► Exercise.
Variables and Expressions Programming Right from the Start with Visual Basic.NET 1/e 7.
Controlling Program Flow with Decision Structures.
Visual Basic Review LBS 126. VB programming Project Form 1Form 2Form 3 Text boxButton Picture box Objects Text box Button Objects.
Microsoft Visual Basic 2012 CHAPTER FIVE Decision Structures.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
Financial Information Management VB, VBA, VS, VSTO & VBE: Putting it all together Source: Excel VBA Programming by John Walkenbach.
© Stefano Grazioli - Ask for permission for using/quoting: Source: Excel VBA Programming by John Walkenbach.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Chapter 6 Controlling Program Flow with Looping Structures.
© 2010 Lawrenceville Press Slide 1 Chapter 5 The Do…Loop Statement  Loop structure that executes a set of statements as long as a condition is true. 
COMPREHENSIVE Excel Tutorial 12 Expanding Excel with Visual Basic for Applications.
VBA - Excel VBA is Visual Basic for Applications
Visual Basic 6 (VB6) Data Types, And Operators
Exploring Microsoft Excel
Introduction to Computer Programming IT-104
Presentation transcript:

Visual Basic Objects / Properties / Methods PropertyAdjective ObjectNoun Part of the application Attribute MethodVerb Action to do something

Visual Basic Range (“A3”).select Range is an object select is a method (“A3”) is a modifier for the object Note that object separated from method by a.

Activesheet.name Activesheet is an object name is a property Visual Basic The result is the name of the active sheet

Procedures Sub procedures return no values except by changes to parameters in the argument list Function procedures return a value by assigning it to the name of the function.

Function Procedures Function Grade (exam1,exam2,exam3) as String Sum = exam1+exam2+exam3 If Sum > 95 then Grade = “A” Elseif Sum > 80 Grade = “B” Else Grade = “C” Endif End Function Dim Sum as Single

For functions and sub procedures, there is a one to one correspondence between the arguments in the call to the function and the argument list of the function: Function Grade (exam1,exam2,exam3) as String The call: = Grade( 90, C40, $C$60 ) The definition:

Sub Procedures Public Sub ColorList() ' Lists all the available colors in the current pallette ' Number is listed in column 2, color sample in column 3 ' List starts in row 5 Dim I As Integer Dim J As Integer Dim K As Integer J = 5 I = 2 For K = 1 To 56 Cells(J, I).Value = K Cells(J, I + 1).Interior.ColorIndex = K J = J + 1 Next K End Sub Note that ColorList is never assigned a value!

Review of some Excel Basics Cell references of two types: A1 Columns are alphabetic, rows are numeric R1C1 R number Column number B2 and R2C2 refer to the same cell Can be set by the Tools / Options menus (Note that the two methods are transposed – A1 – column first, then row R1C1 – row first, then column )

Formulae in Excel (R1C1 style) R1C1 is an absolute address – it does not change under copy / paste R[1]C[1] is a relative address – it does change under copy /paste And can use mixed mode: R1C[1] – R1 is absolute, C[1] is relative

In VBA, can use either or both A1 and R1C1 styles A1 style tends to be absolute A1 style used with the “Range” object Range(“A4”) Can refer to individual cells with the “Cells” object, which uses an R1C1 style Cells(4,1)

In Excel, cells & ranges can be named Insert / name menu These names can be used in Formulae VBA

VBA Variable Types String A sequence of bytes containing characters Integer 2 byte integer Long 4 byte integer Single 4 byte real number Double 8 byte real number VariantCan hold anything (but “expensive” to use) “Object”A class of data types used by Excel/VBA

Characters & Stings For Excel, anything that is not a number or a formula is a string. If want a set of digits as a string, need to enclose in quote or quotation marks. For VBA, need to define variable that will hold strings as string data types

Visual Basic Sub NameIt() Dim newname as String newname = InputBox(“Enter a name for the worksheet”) ActiveSheet.Name=newname End Sub Example -- simple Sub to name the active worksheet:

“Object” data type Many of the objects in Excel have their own data type: Dim r as Range Dim q as Worksheet Dim z as Chart About the only one we will use is the “Range” data type.

Option Explicit Forces you to ‘Dim’ all variables Helps prevent typos Can set this as the default through the Tools/ Options menu. (Require variable declaration check box)

Visual Basic All objects have properties Most objects have methods Will work with only a few of the many objects, methods and properties To get a list of objects and properties, invoke the Object Browser (F2)

Program module (Sub or Function) is made up of a series of steps to accomplish a task. Five major categories of steps: Assignment statements A = 5 Conditional statementsIf ( A > 5) then …. Calls to other modulesA = sqrt (12) Input /Output operations (Which are really calls to other modules) Read 5, A Iteration Statements For I = 1 to 6 … Next i

Expression evaluation inVBA Operators in priority order Left to right Operator Priority List ( ) ^ - (unary minus) * / + - Comparison Operators (>, < …) Logical Operators (NOT, AND, OR…)

Test = ^2 > 5 AND (3-7)*2 > 6 (3-7)-4 3^2 9 -4* > 5True -8 > 6False True AND FalseFalse Thus, Test has the value “False”

Conditional Expressions If / then / else end if Select case …. End Case

If (expression) then One or more expressions Else One or more expressions End If If (expression ) then (expression) Note: no End If statement for this type of If /then expression

Select Case testexpression [Case expressionlist-n [statements-n]]... [Case Else [elsestatements] ] End Select Select Case Statement Like a complex If / Then / ElseIf … / EndIf

Select Case Statement Testexpression can be any that evaluates to a numeric value or a string Expressionlist is compared to the testexpression to determine if the following statements should be executed. See “Help” for all the allowable forms Statements are executed up to the next Case statement or the End Select statement

A simple example Case statements to determine a letter grade from a numeric grade. Assume the numeric grade is in the variable “grade”

Select Case grade Case Is >=90 ltrgrade=“A” Case Is >= 85 ltrgrade = “BA” … Case Is >= 70 ltrgrade = “C” Case Else ltrgrade=“E” End Select Note: Goes to first Case that testexpression satisfies. Is implicitly uses grade in the comparison

Generally speaking, anything you can do with a Select Case block, you can do with a set of If / Then / Else If … / End If statements

Iteration Statements Used to execute a number of statements repeatedly Two major types --- For / Next Do / Loop

For counter to upperlimt step size Statements Next counter For Each cell In Selection Statements cell.value= expression Next cell

Do statements Loop Basic “ Do Loop” Structure But we need a mechanism to stop the loop!

Do while expression_is_true Statements Loop Do Statements Loop while expression_is_true

Do Until expression_is_true Statements Loop Do Statements Loop Until expression_is_true

Do...Loop Statement Example This example shows how Do...Loop statements can be used. The inner Do...Loop statement loops 10 times, sets the value of the flag to False, and exits prematurely using the Exit Do statement The outer loop exits immediately upon checking the value of the flag. Dim Check, Counter Check = True Counter = 0 ' Initialize variables. Do ' Outer loop. Do While Counter < 20 ' Inner loop. Counter = Counter + 1 ' Increment Counter. If Counter = 10 Then ' If condition is True. Check = False ' Set value of flag to False. Exit Do ' Exit inner loop. End If Loop Loop Until Check = False ' Exit outer loop immediately

To manipulate a cell’s value, use the “value” property of the cell object: Range(“A4”).value = 20 Temp = Range(“A4”).value or Cells(4,5).value = 20 Temp = Cells(4,5).value

Build a simple module to set a 5 x 5 array of cells to some value In VBA IDE Insert module Insert procedure / sub Initcells Dim I as integer Dim J as integer For I = 1 to 5 For J = 1 to 5 Cells(I,J) = I*J Next J Next I Return to Excel and run macro Initcells

Two useful VBA functions to interact with use: Str1 = InputBox(“prompt’) When invoked, displays the prompt and gives you a box to enter a reply, which is placed in Str1 Dim str1 as String str1 = InputBox(“Please enter your name”) InputBox displays a prompt and awaits a reply

MsgBox displays a message and buttons to press. The function value returned is the code for the button J = MsgBox(“prompt”,buttoncodes, “ box name”) Look at ‘Help” for the button code values J is the integer value of the button code the user presses Code=MsgBox(“Are you OK”,vbOKOnly,”My Temp”)

Write a simple sub (called Heater) that accepts a temperature as an argument and returns a string to indicate what to do with the heater. Also have MsgBox display a message to the use if the heater status is changed. The logic for the heater control is as follows: If the temperature is less than 65, “Turn heater on” If the temperature is greater than75, “Turn heater off” Otherwise, “Leave heater alone” Function Heater (Temp) As string Code End function