Introduction to VBA for Excel and its utilization in numerical methods

Slides:



Advertisements
Similar presentations
Introduction to Macro Introduction to Visual Basic for Application Recording a Macro Looking at the code of Recorded Macro.
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.
Developing an Excel Application
Tutorial 8: Developing an Excel Application
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
VBA for MS Excel Hamze Msheik. Open the Visual Basic Editor in Excel 2007 Click on the Microsoft Office button in the top left of the Excel window and.
Microsoft Excel 2003 Illustrated Complete with Excel Programming.
1 Chapter 4 The Fundamentals of VBA, Macros, and Command Bars.
SUNY Morrisville-Norwich Campus-Week 12 CITA 130 Advanced Computer Applications II Spring 2005 Prof. Tom Smith.
Using the Visual Basic Editor Visual Basic for Applications 1.
Adding Automated Functionality to Office Applications.
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.
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.
XP New Perspectives on Microsoft Office Access 2003 Tutorial 11 1 Microsoft Office Access 2003 Tutorial 11 – Using and Writing Visual Basic for Applications.
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.
Microsoft Excel Macros & Excel Solver (IENG490)
Enhancing User Interaction Through Programming
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.
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.
Chapter 11: Introduction to the Visual Basic Environment Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University.
Copyright © 2008 Pearson Prentice Hall. All rights reserved. 1 Microsoft Office Excel Copyright © 2008 Pearson Prentice Hall. All rights reserved
Automating Database Processing Chapter 6. Chapter Introduction Design and implement user-friendly menu – Called navigation form Macros – Automate repetitive.
Copyright © 2008 Pearson Prentice Hall. All rights reserved. 11 Committed to Shaping the Next Generation of IT Experts. Chapter 10 Customizing a Database.
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.
OCC Network Drives  H:\  P:\ 
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
Chapter 9 Macros And Visual Basic For Applications.
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
Introduction to Excel VBA UNC Charlotte CPE/PDH Series December 17, 2009.
Microsoft Excel Illustrated Programming with Excel.
Spreadsheets What is Excel?. Objectives 1. Identify the parts of the Excel Screen 2. Identify the functions of a spreadsheet 3. Identify how spreadsheets.
Introduction to Microsoft Excel Macros COE 201- Computer Proficiency.
Chapter 4 Getting Started with VBA. Subroutines Subroutine is the logical section of code that performs a particular task. Subroutine is also called a.
Controlling Program Flow with Decision Structures.
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
Macros in Excel Using VBA Time Required – 5 hours.
COMPREHENSIVE Excel Tutorial 12 Expanding Excel with Visual Basic for Applications.
The Advantage Series ©2005 The McGraw-Hill Companies, Inc. All rights reserved Chapter 12 Introducing Visual Basic for Applications Microsoft Office Excel.
Excel Tutorial 8 Developing an Excel Application
IE 8580 Module 4: DIY Monte Carlo Simulation
Outline In this module, the following topics will be covered:
Topics Designing a Program Input, Processing, and Output
VBA - Excel VBA is Visual Basic for Applications
VBA - Excel VBA is Visual Basic for Applications
The Selection Structure
Microsoft Access 2003 Illustrated Complete
Microsoft Access Illustrated
Microsoft Office Illustrated
Microsoft Excel 2003 Illustrated Complete
Learning Excel Session 9 and 10 Dr. Chaitali Basu Mukherji.
Introducing VBA Macros
Objectives Learn about Function procedures (functions), Sub procedures (subroutines), and modules Review and modify an existing subroutine in an event.
Computer Programming.
Exploring Microsoft Office Access 2007
VISUAL BASIC.
Exploring Microsoft Excel
Exploring Microsoft® Access® 2016 Series Editor Mary Anne Poatsy
CIS 16 Application Development Programming with Visual Basic
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Microsoft Office Excel 2003
Tutorial 11 Using and Writing Visual Basic for Applications Code
Microsoft Excel 2007 – Level 2
Presentation transcript:

Introduction to VBA for Excel and its utilization in numerical methods Radoslaw Jedynak, PhD Poland, Technical University of Radom Faculty of Teacher Training Department of Mathematics jedynakr@pr.radom.pl

Introduction to Visual Basic for Application - cont… What is Visual Basic? Visual Basic is a language which is inherited from a very popular language BASIC. BASIC stands for Beginners All-purpose Symbolic Instruction Code. Visual Basic is called visual as you can do most of the program by click and go i.e. visually. It’s an event driven & object based language. What is Event Driven Language? When we say event driven it means that you can write triggers which will initiate on specific events for example when user opens any document or saves any document What is Object Based Language? Object based language is language in which we can use objects & their properties i.e. we can use the Worksheet object and its property SheetName when some one clicks on a button

Introduction to Visual Basic for Application - cont… Visual Basic for Application Visual Basic for Application is called VBA as it uses Visual Basic language and is capable of using application specific objects i.e. if we talk about VBA for Excel it can use Cell Object, Range Object, Worksheet Object, Workbook Object etc.

How Excel VBA Works Record, write, or edit recorded VBA code (macros) to automate a complex or repetitive Excel task Macros are saved in our specific Excel workbook or globally Macros can be associated with events; click, double-click, keystroke, etc to run them We may add Windows objects (buttons, dropdown lists, check boxes, textboxes, dialogue boxes, menus, etc..) then write VBA code for each The VB editor (VBE) is a part of Excel to view, edit, and run macros A VB compiler in MS Office executes our code

Enabling the Developer Tab Click on Office Button Click on Excel Options On Popular Tab check Show Developer tab in Ribbon

The VBA Ribbon in 2010/2007 The Developer tab appears on the Excel ribbon Buttons are pointed to

Macro Security in Excel 2010 / 2007 To set up the macro security settings in Excel 2010 or Excel 2007, execute the following steps.

Macro Security in Excel 2010 / 2007 Here you have four options. The first option will disable all macros. The second option will always ask you to enable a macro. The third option will only allow macros with a digital signature to run, and ask you to enable others. The fourth option will enable all macros.

Visual Basic Editor in Excel 2010 / 2007 To launch the Visual Basic Editor in Excel 2010 or Excel 2007, you can directly click on Visual Basic (or press Alt+F11).

Visual Basic Editor in Excel 2010 / 2007 The Visual Basic Editor appears.

Working with the Visual Basic Editor A project is a collection of macros, worksheets, data-entry forms, and other items that make up the customized application you’re trying to create Project Explorer is the window in the Visual Basic Editor that displays a hierarchical list of all currently open projects and their contents The Project Explorer window is dockable An object is any element within the Excel working environment such as a worksheet, cell, workbook, or even Excel itself

Working with the Visual Basic Editor A property is an attribute of an object that defines one of its characteristics, such as its name, size, color, or location on the screen You can view a list of properties for any object in the Properties window A module is a collection of VBA macros The Code window displays the VBA macro code associated with any item in Project Explorer

Working with the Visual Basic Editor

Working with Sub Procedures A sub procedure performs an action on your project or workbook, such as formatting a cell or displaying a chart A function procedure returns a value A property procedure is used to create custom properties for the objects in your project Syntax refers to the set of rules that specify how you must enter certain commands so that VBA interprets them correctly A comment is a statement that describes the behavior or purpose of a procedure, but does not perform any action

Working with Sub Procedures

Referring to Objects VBA is an object-oriented programming language, in which tasks are performed by manipulating objects

Referring to Objects Objects are often grouped into collections, which are themselves objects, called collection objects

Referring to Objects

Applying Methods A method is an action that can be performed on an object, such as closing a workbook or printing the contents of a worksheet

Working with Variables and Values A variable is a named element in a program that can be used to store and retrieve information Every variable is identified by a unique variable name Dim variable as type

Retrieving Information from the User

Working with Conditional Statements

Creating a Message Box MsgBox Prompt, Buttons, Title

Analyzing VBA Code Selects range object cell A2 Applies bold formatting to range A3:F3 Sets width of columns B-F to AutoFit

Writing VBA Code To write your own code, open the Visual Basic Editor and add a module to the workbook You must follow the formatting rules, or syntax, of the VBA programming language exactly A misspelled keyword of variable name will cause a procedure to fail

Writing VBA Code (cont.) Comments begin with apostrophes Information between quotes will be inserted in the active cell

Writing VBA Code (cont.) Entering code using AutoComplete To assist you in entering the VBA code, the Editor often displays a list of words that can be used in the macro statement Typically the list appears after you press period [.]

Adding a Conditional Statement Sometimes you may want a procedure to take an action based on a certain condition or set of conditions One way to add this type of statement is by using an If...Then…Else statement The syntax for this statement is: If condition then statements Else [else statements]

Adding a Conditional Statement (cont.) Elements of the If…then…Else statement appear in blue

Prompting the User for Data When automating routine tasks, sometimes you need to pause a macro for user input Use the VBA InputBox function to display a dialog box that prompts the user for information A function is a predefined procedure that returns a value Microsoft Office Excel 2007 - Illustrated

Prompting the User for Data (cont.) This text will appear in a dialog box

Debugging a Macro When a macro procedure does not run properly, it can be due to an error, called a bug, in the code To help you find bugs in a procedure, the Visual Basic Editor steps through the procedure’s code one line at a time When you locate an error, you can debug, or correct it

Debugging a Macro (cont.) Indicates that the LeftFooter variable is empty

Creating a Main Procedure Combine several macros that you routinely run together into a procedure This is a main procedure To create a main procedure, type a Call statement for each procedure you want to run

Creating a Main Procedure (cont.) MainProcedure calls each procedure in the order shown Running a main procedure allows you to run several macros in sequence

Working with Data Types Visual Basic supports the usual data types you'd expect to see in any programming language. Table 1 summarizes some of the VBA data types that are used most often for the common sorts of calculations. Table 1. VBA data types Data type Storage Values Boolean 2 bytes True or False Byte 1 byte 0 to 255 Integer −32, 768 to 32,767 Double 8 bytes −1.79769313486231 E 308 to +1.79769313486231 E 308 String Variable ASCII and special characters

Example: Declaring variables using the Dim statement Defining Variables Use the Dim statement to declare a variable, as illustrated in example. Example: Declaring variables using the Dim statement Dim a As Double Dim n As Integer Dim a As Double, Dim b As Double, Dim c As Double Dim d, e, f As Double

Example: Declaring constants Defining Constants VBA constants are declared using the syntax Const Name As DataType = Value Example: Declaring constants Const MyConstant As Integer = 14 Public MyConstant2 As Double = 1.025

Example: Declaring arrays Using Arrays You declare arrays just as you do variables, except you specify the size of the array in the declaration, as shown in Example Arrays are declared with their size specified in parentheses following the array name. Example: Declaring arrays Dim y(1 To 4) As Double Dim x(4) As Double Dim M(1 To 8, 1 To 8) As Double Dim N(8, 8) As Double

Using Conditional Statements If statements start with the If keyword followed by a logical expression, which is followed by the Then keyword. If the logical expression is true, the code between the If statement and the End If statement gets executed. You can also use the Else keyword to define a block of code to execute if the logical expression is false. Further, you can use the ElseIf keyword to test other conditions in a series of If-Then-ElseIf-Then statements. Example: If statements If (time = 32000) then ' Statements go here End If If (MyCondition = True) Then ' Statements Else ' More statements If (count < 10) Then ElseIf (count < 20) Then

Using Loops For i = 1 To n ' Statements go here Next i For most of the common calculations that require looping, plain old For loops will work just fine. In fact, we use For loops probably 90% of the time, but in some special cases Do loops are a better choice. Example: For loop For i = 1 To n ' Statements go here Next i

Example: Two different Do While loops Using Loops Do loops are useful when you're not actually iterating a counter but are testing some condition (a logical statement) instead. In VBA there are actually four different ways of writing Do loops, as shown in Example Example: Two different Do While loops Do While loops execute the loop as long as the condition following the While keyword is true. In this example, the condition is enclosed in parentheses. Note the difference between the two Do While loops. In the first case the condition is tested before the code in the loop is executed, while in the second case the code in the loop is executed once before the condition is tested. This means that in the first case it's possible the code within the loop may not get executed, while in the second case the code within the loop will get executed at least once. Do While (dtime < 32000) ' Statements go here Loop Do Loop While (dtime < 32000)

Example: Two different Do Until loops Using Loops Example: Two different Do Until loops Do Until (dtime > 32000) ' Statements go here Loop Do ' Statments go here Loop Until (dtime > 32000) Do Until loops execute the loop as long as the condition following the Until keyword is false (that is, until the condition becomes true). As with Do While loops, there are two ways to write Do Until loops. In the first case shown in Example the condition is tested before the code within the loop is executed, while in the second case the code in the loop is executed before the condition is tested.

Some useful VBA fuctions Function Comment Abs( number ) Returns the absolute value of the number argument. The data type returned is the same as that of the argument. Atn( number ) Returns the arctangent of the number argument. The returned data type is a Double. The result is in radians from -π/2 to π/2. Cos( number ) Returns the cosine of the number argument, which represents an angle in radians. The return type is a Double in the range from -1 to 1. Exp( number ) Returns e raised to the number power. The return type is a Double. Int( number ) Returns the integer part of number, where number is a decimal number. The return type is an Integer. Int essentially truncates the number. To round a number use the Round function. Log( number ) Returns the natural logarithm (to base e) of number. The return type is a Double. To calculate the base 10 log of a number, use the expression Log(number) / Log(10).

Some useful VBA fuctions Function Comment Round( number ) Returns number rounded to the nearest integer. The return type is an Integer. Round( number , n ) Returns number rounded to the nearest decimal place specified by n. The return type is a Double. Sgn( number ) Returns the sign of number. Sgn returns -1 if number is negative, 1 if number is positive, and 0 if number equals zero. Sin( number ) Returns the sine of number, which represents an angle in radians. The return type is a Double in the range from -1 to 1. Sqr( number ) Returns the square root of number. The return type is a Double. Taking the Sqr of a negative number causes an error. Tan( number ) Returns the tangent of number, which represents an angle in radians. The return type is a Double.

Calling VBA functions num1 = 1 - cos(1.571) num2 = 1 - Atn(a/b) You can call VBA functions in your own expressions, as illustrated in Example num1 = 1 - cos(1.571) num2 = 1 - Atn(a/b)

The Real Roots of a Quadratic Equation Suppose we want to compute the real roots, r1 and r2, of a quadratic equation of the form These roots are given by the well-known equation   Sub Quad() Dim a, b, c, d, r1, r2 as double a = Val(InputBox("Enter a")) b = Val(InputBox("Enter b")) c = Val(InputBox("Enter c")) MsgBox ("a = " & a & " b = " & b & " c = " & c) d = b*b - 4*a*c MsgBox (" discriminant = " & d) r1 = (-b + sqr(d))/(2*a) r2 = (-b - sqr(d))/(2*a) MsgBox( " root 1 = " & r1 & " root2 = " & r2) End Sub

Numerical Methods with Excel/VBA Numerical Integration Idea: approximate the integral by sums over trapezoidal areas :

Numerical Integration Trapezoid rule for integration: Let us write a module (program) for this: Input: a - lower integration limit b upper integration limit n number of subdivisions some function f(x) which we want to integrate Output: approximate value for the integral

Numerical Integration Sub Nint() a = 0 b = 5 n = 100 h = (b - a) / n I = h * (f(a) + f(b)) / 2 For m = 2 To n I = I + f(a + h * (m -1)) * h Next Range("B3").Value = I End Sub Function f(x) f = x ^ 4 End Function Put the result onto the Excel sheet into the cell B3

Numerical Integration Example 2 Example 1 Example 3

Numerical Integration Example 3 How do we deal with infinity? Introduce a cut-off at some value large enough such that the mistake is small. This is possible because the integrant falls off sharply after certain values: Compute instead:

Numerical Integration Different types of methods: Simpson’s 3/8 rule (based on four adjacent points): Function Nintff(a, b, n) h = (b - a) / n I = 0 For m = 1 To n - 2 Step 3 I = I + (f(a+h*(m-1)) +3* f(a+h* m) +3* f(a+h*(m+1))+f(a+h*(m+2))) Next Nintff = I * h * 3 / 8 End Function Example 1

Thank you for your attention