Download presentation
Presentation is loading. Please wait.
Published byIngeborg Bergström Modified over 6 years ago
1
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
2
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
3
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.
4
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
5
Enabling the Developer Tab
Click on Office Button Click on Excel Options On Popular Tab check Show Developer tab in Ribbon
6
The VBA Ribbon in 2010/2007 The Developer tab appears on the Excel ribbon Buttons are pointed to
7
Macro Security in Excel 2010 / 2007
To set up the macro security settings in Excel 2010 or Excel 2007, execute the following steps.
8
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.
9
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).
10
Visual Basic Editor in Excel 2010 / 2007
The Visual Basic Editor appears.
11
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
12
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
13
Working with the Visual Basic Editor
14
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
15
Working with Sub Procedures
16
Referring to Objects VBA is an object-oriented programming language, in which tasks are performed by manipulating objects
17
Referring to Objects Objects are often grouped into collections, which are themselves objects, called collection objects
18
Referring to Objects
19
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
20
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
21
Retrieving Information from the User
22
Working with Conditional Statements
23
Creating a Message Box MsgBox Prompt, Buttons, Title
24
Analyzing VBA Code Selects range object cell A2
Applies bold formatting to range A3:F3 Sets width of columns B-F to AutoFit
25
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
26
Writing VBA Code (cont.)
Comments begin with apostrophes Information between quotes will be inserted in the active cell
27
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 [.]
28
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]
29
Adding a Conditional Statement (cont.)
Elements of the If…then…Else statement appear in blue
30
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 Illustrated
31
Prompting the User for Data (cont.)
This text will appear in a dialog box
32
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
33
Debugging a Macro (cont.)
Indicates that the LeftFooter variable is empty
34
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
35
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
36
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 − E 308 to E 308 String Variable ASCII and special characters
37
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
38
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
39
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
40
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
41
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
42
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)
43
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.
44
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).
45
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.
46
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)
47
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
48
Numerical Methods with Excel/VBA
Numerical Integration Idea: approximate the integral by sums over trapezoidal areas :
49
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
50
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
51
Numerical Integration
Example 2 Example 1 Example 3
52
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:
53
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
54
Thank you for your attention
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.