Final Exam Review: VBA

Similar documents
Chapter 5 Functions. Introducing Functions

FX 260 Training guide. FX 260 Solar Scientific Calculator Overhead OH 260. Applicable activities

Getting Started with MasteringPhysics

Excel & Visual Basic for Applications (VBA)

DATA 301 Introduction to Data Analytics Microsoft Excel VBA. Dr. Ramon Lawrence University of British Columbia Okanagan

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

VB.NET Programming Fundamentals

Excel & Visual Basic for Applications (VBA)

A Concise Guide for Beginners LIEW VOON KIONG

This activity will guide you to create formulas and use some of the built-in math functions in EXCEL.

Module 2 - Multiplication Table - Part 1-1

1. a procedure that you perform frequently. 2. Create a command. 3. Create a new. 4. Create custom for Excel.

OpenOffice.org 3.2 BASIC Guide

The OptQuest Engine Java and.net Developer's Guilde

Microsoft' Excel & Access Integration

Programming in Access VBA

0 Introduction to Data Analysis Using an Excel Spreadsheet

Below is a very brief tutorial on the basic capabilities of Excel. Refer to the Excel help files for more information.

Exercise 4 Learning Python language fundamentals

MATLAB Basics MATLAB numbers and numeric formats

Graphing Calculator Scientific Calculator Version 2.0

Hands-on Exercise 1: VBA Coding Basics

fx-92b Collège 2D+ User s Guide CASIO Worldwide Education Website CASIO EDUCATIONAL FORUM

SOME EXCEL FORMULAS AND FUNCTIONS

Visual Logic Instructions and Assignments

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Chapter 5 Programming Statements. Chapter Table of Contents

MS Excel. Handout: Level 2. elearning Department. Copyright 2016 CMS e-learning Department. All Rights Reserved. Page 1 of 11

Microsoft Access 2010 Part 1: Introduction to Access

Construction Administrators Work Smart with Excel Programming and Functions. OTEC 2014 Session 78 Robert Henry

Using Excel to Execute Trigonometric Functions

TI-Nspire CAS Graphing Calculator

User Guide.

Microsoft Excel Tutorial

Introduction. Syntax Statements. Colon : Line Continuation _ Conditions. If Then Else End If 1. block form syntax 2. One-Line syntax. Do...

Chapter One Introduction to Programming

Word 2010: Mail Merge to with Attachments

Creating Datalogging Applications in Microsoft Excel

Introduction to Microsoft Access 2003

fx-83gt PLUS fx-85gt PLUS User s Guide

Creating Applications using Excel Macros/Visual Basic for Applications (VBA)

MATLAB Programming. Problem 1: Sequential

Creating a Simple Macro

Getting Started with Access 2007

VBA PROGRAMMING FOR EXCEL FREDRIC B. GLUCK

Financial Data Access with SQL, Excel & VBA

C Programming Language

Display Format To change the exponential display format, press the [MODE] key 3 times.

RIT Installation Instructions

Like any function, the UDF can be as simple or as complex as you want. Let's start with an easy one...

3.4 System Dynamics Tool: STELLA Version 9 Tutorial 2. Introduction to Computational Science: Modeling and Simulation for the Sciences

2. Descriptive statistics in EViews

The KmPlot Handbook. Klaus-Dieter Möller Philip Rodrigues David Saxton

MICROSOFT EXCEL FORMULAS

Plots, Curve-Fitting, and Data Modeling in Microsoft Excel

Excel. Microsoft Office s spreadsheet application can be used to track. and analyze numerical data for display on screen or in printed

Parameters and Expressions

What is Microsoft Excel?

InTouch HMI Scripting and Logic Guide

Almost all spreadsheet programs are based on a simple concept: the malleable matrix.

Using Excel and VBA CHANDAN SENGUPTA SECOND EDITION. WILEY John Wiley & Sons, Inc.

Visual Basic Programming for Excel

Programming MS Excel in Visual Basic (VBA)

Tutorial 2: Using Excel in Data Analysis

FX 115 MS Training guide. FX 115 MS Calculator. Applicable activities. Quick Reference Guide (inside the calculator cover)

MS Access Lab 2. Topic: Tables

AIMMS Function Reference - Arithmetic Functions

BA II Plus. Guidebook. Texas Instruments Instructional Communications. Dave Caldwell David Santucci Gary Von Berg

Performing Simple Calculations Using the Status Bar

Sample- for evaluation only. Advanced Excel. TeachUcomp, Inc. A Presentation of TeachUcomp Incorporated. Copyright TeachUcomp, Inc.

A Microsoft Access Based System, Using SAS as a Background Number Cruncher David Kiasi, Applications Alternatives, Upper Marlboro, MD

Using Object- Oriented JavaScript

MODELLING. IF...THEN Function EXCEL Wherever you see this symbol, make sure you remember to save your work!

Microsoft Excel 2010 Tutorial

Introducing VBA Message Boxes

Chapter 12 Programming Concepts and Languages

ESPResSo Summer School 2012

Excel 2007 Basic knowledge

Gerrit Stols

Designed by Jason Wagner, Course Web Programmer, Office of e-learning ZPRELIMINARY INFORMATION... 1 LOADING THE INITIAL REPORT... 1 OUR EXAMPLE...

MS Access: Advanced Tables and Queries. Lesson Notes Author: Pamela Schmidt

Algebra. Exponents. Absolute Value. Simplify each of the following as much as possible. 2x y x + y y. xxx 3. x x x xx x. 1. Evaluate 5 and 123

Microsoft Excel 2013: Macro to apply Custom Margins, Titles, Gridlines, Autofit Width & Add Macro to Quick Access Toolbar & How to Delete a Macro.

Excel macros made easy

5: Magnitude 6: Convert to Polar 7: Convert to Rectangular

Excel Spreadsheets: Getting Started

EXCEL Tutorial: How to use EXCEL for Graphs and Calculations.

EXCEL SPREADSHEET MANUAL

Using Loops to Repeat Code

Statgraphics Getting started

Microsoft Excel 2010 Part 3: Advanced Excel

Using the Advanced Tier Data Collection Tool. A Troubleshooting Guide

Review of Matlab for Differential Equations. Lia Vas

Excel Level Two. Introduction. Contents. Exploring Formulas. Entering Formulas

National Database System (NDS-32) Macro Programming Standards For Microsoft Word Annex - 8

The FTS Real Time System lets you create algorithmic trading strategies, as follows:

Transcription:

Engineering Fundamentals ENG1100 - Session 14B Final Exam Review: VBA 1 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

Final Programming Exam Topics Flowcharts Assigning Variables Flow Control Conditional Statements For Loops Functions Definition Line How to call What is returned to the spreadsheet Macros (sub) Definition Line How do you get variables into/out of sub 2 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

What is going on?? Function sind(angle) 'Function to compute the sine of 'an angle in degrees 'angle=angle, degrees 'calculate the value for pi Pi = 4 * Atn(1) 'calculate sine sind = Sin(angle * Pi / 180) End Function All functions start with a line defining the function Function name(arguments) Calculations One calculation must be named the same as your function. The function outputs this value when the function is used. VBE puts this here automatically 3 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

The Concept of Assignment Information within program is stored: Directly as constant (example, 9.81), whose value does not change Symbolically as a variable (a=9.81), whose value can be changed = 10 4 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi a Variable (memory location) Assignment Constant (Value) Assignments must have: single variable on left valid value on right

Equal Sign In programming the equal sign means: Is replaced by Is assigned the result of Valid assignment examples: c=a+b, x=x+1 Equal sign does NOT mean equality as in algebra Invalid assignment examples: a+b=c; 3=x+y+99 5 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

What is going on?? Function sind(angle) 'Function to compute the sine of 'an angle in degrees 'angle=angle, degrees 'calculate the value for pi Pi = 4 * Atn(1) 'calculate sine sind = Sin(angle * Pi / 180) End Function These are comments. They are important. VBA has some functions (like Atn* and Sin) but doesn't have others (like Pi) *Atn is arctangent 6 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

Some Built-In Numeric VBA Functions Purpose VBA Function Excel Function Absolute value Abs(x) ABS(x) Truncate to integer Int(x) INT(x) Round x to n digits after decimal Round(x,n) ROUND(x) Square root Sqr(x) SQRT(x) Exponential, e Exp(x) EXP(x) Natural log Log(x) LN(x) Base-10 log - LOG10(x) Base-b log - LOG(x,b) Value of pi - PI() Sine Sin(x) SIN(x) Cosine Cos(x) COS(x) Tangent Tan(x) TAN(x) Arcsine - ASIN(x) Arccosine - ACOS(x) Arctangent Atn(x) ATAN(x) Arctangent (4 quadrant) - ATAN2(x,y) Degrees to radians - RADIANS(x) Radians to degrees - DEGREES(x) X modulo y X Mod y MOD(x,y) Random number Rnd() RAND() Bold indicates functions that differ between VBA and Excel. Table from: Chapra, S.C. Power Programming With VBA/EXCEL, pg. 93. 7 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

Using Excel Functions in VBA Some functions can be called from Excel to use in your VBA code. Calling an Excel function in VBA: Application.WorksheetFunction.functionname(argum ent) Example: inverse cosine of 0.5 Application.WorksheetFunction.acos(0.5) Do a help search on Visual Basic Functions List of Worksheet Functions Available to Visual Basic Using Microsoft Excel Worksheet Function in Visual Basic 8 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

Sending Multiple Arguments to a Function A 2 +B 2 =C 2 VBA Function Hyp(A,B) 9 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

Flowchart Symbols Start Start or Stop Input X,xmin Input or Output x=xmin+5 Process Step? Test for Branching Flow of Process Graphically represent sequential problems and decision choices. Typical Symbols are: Start/Stop Input/Output Process Step Test for Branching (decision) Flow of Process 10 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

If/Then/Else Statements in VBA VBA syntax for an if/then/else statement: If condition Then True statements Else False statements End If Indentation is IMPORTANT 11 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

If/Then Statements in VBA Do not need to include the else if it's not needed VBA syntax for an If/Then statement If condition Then True statements End If 12 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

If/Then/ElseIf Statements in VBA Can also have nested If statements VBA syntax for an If/Then/ElseIf statement If condition 1 Then True statements 1 ElseIf condition 2 Then True statements 2 Else False statements End If 13 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

Loops Used for repetitive calculations For Loops Continue loop for known number of times Repetitively execute statements 14 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

For/Next Loop If we know that the loop should run n times, there is a special loop to deal with these cases. For/Next loop VBA syntax: For counter = start To finish Statements Next counter 15 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

Start Factorial Function N = number i fact_calc Initialize variable: fact_calc=1 For i=1 to N fact_calc=fact_calc*i fact_calc End T F Function fact_calc(n) This Function will calculate the Factorial of n initialize fact_calc fact_calc=1 For i = 1 To n fact_calc = fact_calc * i Next i End Function =6*4 = 24 =fact_calc*i =24*5 = 120 16 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi 1 2 3 4 5 =fact_calc*i =1*1 = 1 =fact_calc*i =1*2=2 =fact_calc*i =2*3 = 6 =fact_calc*i

For/Next Loop Options Specifying step size For counter = start To finish Step increment Statements Next counter Default step size is one. If you want a different step size you can specifiy it. Example: For i = 1 To 10 Step 2 Will count: 1,3,5,7,9 17 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

For/Next Loop Options Alternative way of exiting the loop: For counter = start To finish Statements If condition Then Exit For Statements Next counter The loop will terminate when it encounters an Exit For statement. Any number of Exit For statements may be placed in the loop. Exit For statements may be placed anywhere. 18 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

Functions Review We can now write our own functions in Excel Functions are good for... Doing repetitive calculations Returning a single value (answer) to the cell What if we want to do more?... 19 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

Writing Macros Ability to do many, many things including: Formatting cells Performing calculations Grabbing data from cells Putting data into cells Display pop-up messages, dialog and input boxes And more... Let's start with a simple example. 20 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

Option Explicit Sub Factorial() 'Names, Section #, Team # 'Date 'Variable Declaration Dim n As Single, c As Single, initial As Single Dim i as Integer 'input data Sheets("Sheet1").Select Range("B8").Select n = ActiveCell.Value Initial =1 'calculation For i = 1 To n 'compute factorial c = initial * i initial = c Next i 'output results Range("B9").Select ActiveCell.Value = c What is going on?? Forces you to define the type of all variables (good programming practice). Declaring the macro program to be a subroutine program, Factorial. The parentheses are for the routine's arguments. In this case, there are no arguments. Defining the variable types End Sub 21 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

Declaring Variables Why declare variables? Macros will run faster and use less memory You will avoid problems with misspelled variable names VBA syntax for declaring variables: Dim varname As type, varname As type,... Good practice to: Place all your Dim statements at the beginning of the program. Group them by type. Option Explicit Sub Example() 'Variable declaration Dim i As Integer, n As Integer Dim t As Long Dim x As Single, v As Single Dim z As Double... 22 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

Numeric Variable Types Integers (whole numbers used for counting) Integer type (range from -32,768 to 32,757 or 2 bytes) Long type (range from -2,147,483,648 to 2,147,483,647 or 4 bytes) Real or floating-point (decimal numbers used for measuring) Single type (about 7 significant digits of precision or 4 bytes) Good for most engineering and scientific calculations Double type (about 15 significant digits of precision or 8 bytes) 23 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

Variant Data Type Your code will work if you declare the variables like this, but not as you may expect... Dim x, v As Single VBA will make the following assignments: v is a single type x is a variant type The variant type allows the macro to choose which data type it should be. Warning: this will slow down your macro. 24 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

Option Explicit Sub Factorial() What is going on?? 'Names, Section #, Team # 'Date 'Variable Declaration Dim n As Single, c As Single, initial as Single Dim i as Integer 'input data Sheets("Sheet1").Select Range("B8").Select n = ActiveCell.Value Initial =1 'calculation For i = 1 To n 'compute factorial c = initial * i initial = c Next i 'output results Range("B9").Select ActiveCell.Value = c End Sub Grabbing data from your spreadsheet and assigning the values to variables Outputting value of variable c to cell B9. These are Object-Oriented Programming (OOP) statements 25 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

More Useful OOP Statements Clear a section of the worksheet Range( t3:z40 ).ClearContents Move the current active cell ActiveCell.Offset(0,1).Select Moves the active cell 0 rows, 1 column to the right ActiveCell.Offset(1,0).Select Moves the active cell 1 row down, 0 columns 26 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

Running The Program Go back to Excel Go to: Tools Macro Macros Select the macro you want (Factorial) Click the run button Or.. Go to: View Toolbars Forms In the forms toolbar select the button button (rectangle) Size the button on your spreadsheet In the Assign Macro dialogue box, select Factorial Rename the button to something descriptive like Run Factorial 27 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi

Simple Factorial Program Results... A B C D 1 Simple Factorial Addition Program Program 2 3 Names 4 Section ## Run 5 Team ## 6 Date 7 Final Value 5 8 First Number 12 Factorial 120 9 Section Number 9 10 11 Total 21 28 //coe/dfs/home/engclasses/eng1101/f03/ethics/en1.e05.finalcoursewrapup.sxi