Week 2.  Macros revisited  The VBA Editor  The object model  Using variables  If statements.

Slides:



Advertisements
Similar presentations
Integrated Business Applications with Databases (D3) Jenny Pedler
Advertisements

ISOM3230 Business Applications Programming
PROGRAMMING IN VISUAL BASIC PART 1
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
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
Programming in Visual Basic
String Variables Visual Basic for Applications 4.
VBA & Excel Barry L. Nelson IEMS 465 Fall Quarter 2003.
COMPREHENSIVE Excel Tutorial 8 Developing an Excel Application.
Exploring Microsoft Excel 2002 Chapter 8 Chapter 8 Automating Repetitive Tasks: Macros and Visual Basic for Applications By Robert T. Grauer Maryann Barber.
Week 1.  Kate Watson  Checked at least every other day. Queries and general comments welcome.
Variables and Constants
McGraw-Hill/Irwin Copyright © 2013 by The McGraw-Hill Companies, Inc. All rights reserved. Extended Learning Module M Programming in Excel with VBA.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #4: Working with Variables and User Interfaces IE 212: Computational Methods for Industrial Engineering.
Project 9 Using Visual Basic for Applications (VBA) to Customize and Automate Excel Jason C. H. Chen, Ph.D. Professor of Management Information Systems.
© McGraw-Hill Companies, Inc., McGraw-Hill/Irwin Extended Learning Module M Programming in Excel with VBA.
McGraw-Hill/Irwin Copyright © 2013 by The McGraw-Hill Companies, Inc. All rights reserved. Extended Learning Module M Programming in Excel with VBA.
Automating Tasks with Visual Basic. Introduction  When can’t find a readymade macro action that does the job you want, you can use Visual Basic code.
Creating Macros Using VBA. Assigning a Macro to a Button Display the Forms toolbar. Click the Button icon. Click and drag the mouse pointer to specify.
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)
Copyright © 2008 Pearson Prentice Hall. All rights reserved. 1 Microsoft Office Excel Copyright © 2008 Pearson Prentice Hall. All rights reserved
Chapter 4: The Selection Process in Visual Basic.
Visual Basic for Applications Macro Programming For Microsoft Office.
 Application – another name for a program.  Interface – is what appears on the screen when the application is running.  Program Code – is instructions.
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.
Microsoft Visual Basic 2005 CHAPTER 4 Variables and Arithmetic Operations.
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”
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
Chapter 3 The Visual Basic Editor. Important Features of the VBE Alt-F11 will open the Visual Basic Editor. The Code window is to the right, Project Explorer.
Variables & Function Calls. Overview u Variables  Programmer Defined & Intrinsic  Data Types  Calculation issues u Using Functions  The val() function.
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 2 Introduction to VBA (II) ► Lab 1 revisited - Sub & Function procedures - Data types and variable declaration ► Recording.
Chapter 11: Introduction to VBA Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
1 Scripting Languages VBScript - Recognized mainly by Internet Explorer only - Netscape does have a plug-in JavaScript - Recognized by Internet Explorer.
# 1# 1 What is a variable that you create? What is a constant that you create? What is an intrinsic (built-in) constant? What variables are built in?
Hungarian Notation A must in this course Every object used MUST be renamed including the form(s) using the following rules Form  frmFormName E.g. frmTemperature.
Lab 10. User Forms Design – Code Part ► Lab 9 Review ► Continue ‘Student Record’ Example ► A Car Loan Application.
Visual Basic Objects / Properties / Methods PropertyAdjective ObjectNoun Part of the application Attribute MethodVerb Action to do something.
Chapter 4 Getting Started with VBA. Subroutines Subroutine is the logical section of code that performs a particular task. Subroutine is also called a.
CECS 5020 Computers in Education Visual Basic Variables and Constants.
Slide 1 Controls v Control naming convention –Label: lblName –Command Button: cmdName –Text Box: txtName.
Variables and Expressions Programming Right from the Start with Visual Basic.NET 1/e 7.
Controlling Program Flow with Decision Structures.
Microsoft Visual Basic 2012 CHAPTER FOUR Variables and Arithmetic Operations.
Visual Basic.NET Programming for the Rest of Us Keith Mulbery Utah Valley State College.
Creation of Variables with Numeric, alphanumeric, date, picture, memo data types Constant - A quantity that does not change during the execution of a program.
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
COMPREHENSIVE Excel Tutorial 12 Expanding Excel with Visual Basic for Applications.
Microsoft Visual Basic 2010 CHAPTER FOUR Variables and Arithmetic Operations.
Excel Tutorial 8 Developing an Excel Application
IE 8580 Module 4: DIY Monte Carlo Simulation
A variable is a name for a value stored in memory.
Arithmetic operations and operators, converting data types and formatting programs for output. Year 11 Information Technology.
VBA - Excel VBA is Visual Basic for Applications
VBA - Excel VBA is Visual Basic for Applications
Data Types, Arithmetic Operations
Variables and Arithmetic Operations
Microsoft Access Illustrated
Microsoft Office Illustrated
Variables and Arithmetic Operations
Chapter 6 Variables What is VBScript?
Exploring Microsoft Excel
Visual Basic Programming Chapter Four Notes Working with Variables, Constants, Data Types, and Expressions GROUPBOX CONTROL The _____________________________________.
Presentation transcript:

Week 2

 Macros revisited  The VBA Editor  The object model  Using variables  If statements

 Record a macro that formats highlighted cells to appear as integers (enter some decimal numbers to test it on)  Create a Message Box that looks like this:  (tip the icon is called vbInformation)

 Your macro might look something like this: Sub Macro2() ' ' Macro2 Macro ' Selection.NumberFormat = "0.00" Selection.NumberFormat = "0.0" Selection.NumberFormat = "0" End Sub

 Your macro should look something like this: Sub IntegerFormat() ' Format highlighted cells as integer Selection.NumberFormat = "0.00" Selection.NumberFormat = "0.0" Selection.NumberFormat = "0" End Sub

 Your macro should look something like this: Sub IntegerFormat() ' Format highlighted cells as integer With Selection.NumberFormat = “0“ End With End Sub

 Formatting Fonts  Record a new macro to format the selected cells as follows: Tahoma, Bold, Size 14  Edit your macro using With Selection.Font ensuring that there is no unnecessary code (don’t forget to End With)

 User friendly environment for writing VBA code  Access the VBE by pressing Alt-F11  The programming workspace includes: The Code window The Project Explorer  Worksheets + Chart Sheets  ThisWorkbook  Modules (for VBA code)  User forms (for dialog boxes) The Properties Window

Project explorer Properties window Code window Immediate window

1. Provide sufficient comments Start the line with a single quote The line is coloured green and ignored by VBA 2. Indent consistently Provide a logical structure to your program 3. Use white space liberally  Use Names wisely – “Macro1” is fine now, but less helpful for future reference 10

 Objects Car, Engine, Spark plugs, Door(s)  Properties (Values) Colour (red), Type (1.4l), Age (4 years), size (4- door), Locked (True)  Methods (arguments) Do Locking (central), Turn over, Spark, Drive (10mph), Reverse  Events Hit wall, Reach speed limit, Driver turns key

 Examples of Objects: Ranges, worksheets, charts, workbooks  Each object has properties, i.e. the attributes of the object e.g., a cell has a Value property (either text or number in the cell), a Formula property (the formula in the cell) and a HorizontalAlignment property (left, center or right).

The Object Model  Each object has methods, i.e. the things you can do to an object e.g., a cell has the ClearContents method to erase the content of the cell (equivalent to the delete key).  Some methods have arguments, i.e. qualifiers indicating how a method is performed e.g., the Copy method has a Destination argument.

 Objects can be manipulated using the collections they belong to, specifying their location in the object hierarchy using the dot notation. Worksheets(“Sheet1”) Worksheets(1) Workbooks(“Book1”).Worksheets(“Sheet1”) Worksheets(“Sheet1”).Range(“A1”) Application.Workbooks(“Book1”)._ Worksheets(“Sheet1”).Range(“A1”)

 Online help tool.  Click on the Object Browser button in the Standard toolbar.  Select Excel Libraries List of all objects (on the left) List of properties and methods for each object (on the right)  Properties: hand icon  Methods: green rectangular icon  To get help on any item, select it and click on the question mark button.

Variables Variable: A variable is a mechanism which enables you to store information and use it while a program is running. As the name implies, it is possible to change the value during the running of a program

Variables Option explicit Sub hello() Dim username As String username = InputBox("Please enter your name") MsgBox "Hello " & username End Sub

Variable names  Valid variable names can contain text or numbers but they must use a letter as the first character.  You can't use a space, period (.), exclamation mark (!), or the /, &, $, # in the name.  Names cannot exceed 255 characters in length (short and to the point is best)  Be descriptive

Variable types  Byte  Integer  Long  Single  Double  Currency  Boolean  Date  String  Object  Variant 0 to to bn to 2.1 bl Regular decimal numbers Large decimal numbers trn to 9.22 True / False 1/1/100 to 31/12/9999 “2bn characters” Any object reference Avoid

Variable names and types  Suggest suitable variable names and types for variables representing: GDP of a country Client name Client reference number Price of an item of stock Number of items in stock Number of staff in a department Agent’s commission rate Invoice due date Invoice state (paid or unpaid)

Exercises  Open week3.xls  Open the VBE and look at the Macro Orders Why won't it run? Can you fix the errors?

Declaring and assigning variables  Variables are declared to exist within a program  A variable can be initialised with a value  A variable can have different value while a program runs  Dim xxxx As type Dim stands for dimension As assigns type Dim x, y, z as integer (wrong) Dim x as integer, y as integer, z as integer (correct)

Option Explicit Sub Example() Dim x As Byte x = InputBox (“Enter a number between 1 and 10”) MsgBox x End Sub  Use Option Explicit at the head of a module to force variable declaration  You can automatically use Option Explicit Tools>Options>Require variable declaration

Assigning variables  Variable on the LHS, Value on the RHS  x = 1 the value 1 is assigned to x  SalesRegion = “North West” use double quotes when assigning string variables   NextFinYear = #1-April-2009# Use # to enclose the value of a date, NB date format defaults to US (very inconvenient!)

Assigning variables  DeliveryDate = OrderDate + 3  y = x a variable y is assigned the value of x  OrderTotal = Subtotal * VatRate  OrderNo = OrderNo + 1 increases the value of a variable called OrderNo by 1 (called incrementing)  y = Range(“B3”).Value

Arithmetical Operators OperatorOperationExampleAnswer + Add Subtract7-25 * Multiply3*515 / Divide10/42.5 \ N1 \ N2 - integer division15\43 Mod X Mod Y returns remainder10 mod 31 ^ X ^ Y gives the value of X raised to the power of Y 2^38

Calculations with variables Sub example1() 'declare variables Dim x as integer, y as integer, z as integer ' assign values to variables x = 3 y = 4 z = x + y ' output result Msgbox z End sub

Using variables sub enterNumbers () Dim Number as Integer number = InputBox("Enter number under 5000", "Enter_ numeric data") number = number * 2 MsgBox "The number multiplied by 2 is " & number, _,,"Greeting Box" End Sub

Concatenation  Concatenation operator & is used to join things together e.g. a number to text. For example: MsgBox "You will be paid " & payrate & " per hour" “&” concatenates string and numeric variables, so you should use it if you want to combine a string and a number  There is also + but this can only concatenate one string to another; if you use it to concatenate a number to text you will get a run-time error

Exercises  Introductory  Reading cells

Constants  Used for a value that recurs but never changes throughout the programme  Const taxRate = 0.28  Can now refer to taxRate during the programme and can easily update the value by changing this one line of code

Built-in Constants  Prefix vb or xl in the Object library ColorConstants Excel Direction

If statements If condition Then doSomething Elseif anotherCondition Then doSomethingElse ElseIf anotherCondition Then doSomethingElse Else doSomethingElse End If =equal to <less than <=less than or equal to >greater than >=greater than or equal to <>not equal to

If statements – an example Sub Profit_Loss () Dim profit As single profit = Range("C1").Value If profit > 0 Then MsgBox "You have made a profit" ElseIf profit = 0 Then MsgBox "You have broken even" Else MsgBox "you have made a loss" End If End Sub

If statements – an example Sub Profit_Loss () If Range("C1").Value > 0 Then MsgBox "You have made a profit" ElseIf Range("C1").Value = 0 Then MsgBox "You have broken even" Else MsgBox "you have made a loss" End If End Sub

Exercises  Pebbles and Muffins

Next week  Assessed Exercise Variables and if statements  Using Ranges in VBA