© Stefano Grazioli - Ask for permission for using/quoting: Source: Excel VBA Programming by John Walkenbach.

Slides:



Advertisements
Similar presentations
Excel and Visual Basic. Outline Data exchange between Excel and Visual Basic. Programming VB in Excel.
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.
Week 10.  Protecting Code  Protecting Worksheets  Error Handling  Charts.
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 Programming Session #2. Things to Review  Variables  Procedures: Subs & Functions  If…Then  For…Next.
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.
Financial Information Management Managing Financial Information Critical Thinking Business Process Modeling WINIT Control Structures Homework.
Using the Select Case Statement and the MsgBox Function (Unit 8)
IE 212: Computational Methods for Industrial Engineering
University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-3 1 Lecture Outline Variable Scope Calling another subprogram Programming.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #4: Working with Variables and User Interfaces IE 212: Computational Methods for Industrial Engineering.
Microsoft Excel 2007 © Wiley Publishing All Rights Reserved. The L Line The Express Line to Learning L Line.
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.
ChE 117 Motivation Lots of Tools Can’t always use “Canned Programs”
# 1# 1 VBA Objects, Message Boxes as Functions What is an object in VBA? How do you move between design mode and run mode? How can you make a cell become.
The animation is already done for you; just copy and paste the slide into your existing presentation. Dony Pranadiyanta, ST.
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.
Week 8.  Recap  User Forms  Input Validation Message Boxes Input Boxes  Conversion Functions.
University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA 1 Lecture Outline Record macro and examine VBA code VBA Editor (IDE)
Week 3.  Assessed Exercise 1  Working with ranges.
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
Programming Examples to Accompany Structure Topic Please use speaker notes for additional information!
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.
Week 4.  Recap – Ranges  For Each Loops  Ranges Referencing Range Objects  Set (keyword)
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Lab 4 Range Review, Control Logic and Loops ► Range Review ► Control Logic and Loops ► Exercise.
Chapter 9 Macros And Visual Basic For Applications.
1 MIS309 Database Systems Introduction to Microsoft Access.
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
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.
Lab 6 (2) Arrays ► Lab 5 (1) Exercise Review ► Array Concept ► Why Arrays? ► Array Declaration ► An Example of Array ► Exercise.
Chapter 11: Introduction to VBA Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
© Stefano Grazioli - Ask for permission for using/quoting:
Introduction to Excel VBA UNC Charlotte CPE/PDH Series December 17, 2009.
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.
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.
Using a Database Access97 Please use speaker notes for additional information!
MIC305 Week 6 Beyond controls Review of properties Differences with VB6: using classes and instances Programming constructs.
© Stefano Grazioli - Ask for permission for using/quoting: Stefano Grazioli.
Financial Information Management VB, VBA, VS, VSTO & VBE: Putting it all together Source: Excel VBA Programming by John Walkenbach.
Macros in Excel Using VBA Time Required – 5 hours.
Lab 5 Arrays ► Lab 4 Exercise Review ► Array Concept ► Why Arrays? ► Array Declaration ► An Example of Array ► Exercise.
VBA Programming for Excel Review Excel Objects Excel Methods Identifying Specific Cells Review Functions for Excel Custom Menus.
Chapter 7 Multiple Forms, Modules, and Menus. Section 7.2 MODULES A module contains code—declarations and procedures—that are used by other files in a.
COMPREHENSIVE Excel Tutorial 12 Expanding Excel with Visual Basic for Applications.
© Stefano Grazioli - Ask for permission for using/quoting: Stefano Grazioli.
Process Automation The Technology
IE 8580 Module 4: DIY Monte Carlo Simulation
Process Automation The Technology
VBA - Excel VBA is Visual Basic for Applications
Spreadsheet-Based Decision Support Systems
Excel VBA Day 3 of 3 Tom Vorves.
Learning Excel Session 9 and 10 Dr. Chaitali Basu Mukherji.
Visual Basic for Applications in Microsoft Excel (1)
Introduction to VBA IE 469 Spring 2018.
Department Array in Visual Basic
Exploring Microsoft Excel
Process Automation: From models to code
Loops, Subs, & Functions Stefano Grazioli.
Loops, Subs, & Functions Stefano Grazioli.
Presentation transcript:

© Stefano Grazioli - Ask for permission for using/quoting: Source: Excel VBA Programming by John Walkenbach

 VBA = VB + Objects (e.g., buttons, cells, charts…)  Objects can contain other objects  Object model (‘Application’ on top)  If plural, then it is a collection of similar objects Application.Workbooks("Book1.xlsx").Worksheets("Sheet1 ").Range("A1")  Objects can contain variables (‘properties’) Application.Workbooks("Book1.xlsx").Worksheets("Sheet1 ").Range("A1").Value

 Objects can contain procedures (‘methods’) Application.Workbooks("Book1.xlsx") _.Worksheets("Sheet1").Range("A1").Clear()  If you omit the top hierarchy, excel uses the active object Range("A1").Value.ToString()

 Specific objects are called instances (e.g., “Button1”)’  The code that generates objects is called a class (e.g., the Class Button ).  A module is just a file that contains code.  Objects (not modules) need to be instantiated with the command New

ActiveWorkbook.Worksheets("Sheet1").Sort _.SortFields.Add Key:=Range("K2:K6"), _ SortOn:=xlSortOnValues, _ Order:=xlDescending, _ DataOption:=xlSortNormal ActiveWorkbook.Worksheets("Sheet1").Sort _.SortFields.Add Range("K2:K6"), _ xlSortOnValues, xlDescending, xlSortNormal

 Copy, paste, and adapt  Fincal Example

Private Sub FinCalBtn_Click(sender As Object, e As EventArgs) Handles FinCalBtn.Click Dim inputFromUser As String = "" Dim interestRate As Double = 0 Dim principal As Double = 0 Dim numberOfYears As Double = 0 Dim interest As Double = 0 Dim sum As Double = 0 Do Range("A1:B2").Clear() Do inputFromUser = InputBox("Hello! Please enter an interest rate (e.g., 4.750)", "User input window", "0") interestRate = Double.Parse(inputFromUser) Loop While (interestRate 10) interestRate = interestRate / 100 Do inputFromUser = InputBox("Please enter a principal (e.g., no $)", "User input window", "0") principal = Double.Parse(inputFromUser) Loop While (principal <= 0) Do inputFromUser = InputBox("Please enter the time in years (e.g.,7)", "User input window", "0") numberOfYears = Double.Parse(inputFromUser) Loop While (numberOfYears 30) inputFromUser = InputBox("Would you like to see: (a) the interest, (b) the sum of principal + interest, or (c) both a and b (default)", "User input window", "c") interest = principal * ((1 + interestRate) ^ numberOfYears - 1) sum = principal + interest Select Case inputFromUser Case "a" Range("A1").Value = interest.ToString("C2") Range("A1").ColumnWidth = 15 Range("B1").Value = "is the interest that you requested" Case "b" Range("A1").Value = sum.ToString("C2") Range("A1").ColumnWidth = 15 Range("B1").Value = "is the sum of interest and principal" Case Else Range("A1").Value = interest.ToString("C2") Range("A1").ColumnWidth = 15 Range("B1").Value = "is the interest that you requested" Range("A2").Value = sum.ToString("C2") Range("B2").Value = "is the sum of interest and principal" End Select inputFromUser = InputBox("Want to compute more? (y/n)", "User Input Window", "n") Loop While inputFromUser = "y" End Sub

Private Sub FinCal() Dim inputFromUser As String Dim interestRate As Double Dim principal As Double Dim numberOfYears As Double Dim interest As Double Dim sum As Double Do Range("A1:B2").Clear Do inputFromUser = InputBox("Hello! Please enter an interest rate (e.g., 4.750)", _ "User input window", "0") interestRate = inputFromUser Loop While (interestRate 10) interestRate = interestRate / 100 Do inputFromUser = InputBox("Please enter a principal (e.g., no $)", "User input window", "0") principal = inputFromUser Loop While (principal <= 0) Do inputFromUser = InputBox("Please enter the time in years (e.g.,7)", "User input window", "0") numberOfYears = inputFromUser Loop While (numberOfYears 30) inputFromUser = InputBox("Would you like to see: (a) the interest, (b) the sum of principal + interest, or (c) both a and b (default)", _ "User input window", "c") interest = principal * ((1 + interestRate) ^ numberOfYears - 1) sum = principal + interest Select Case inputFromUser Case "a" Range("A1").Value = interest Range("A1").ColumnWidth = 15 Range("B1").Value = "is the interest that you requested" Case "b" Range("A1").Value = sum Range("A1").ColumnWidth = 15 Range("B1").Value = "is the sum of interest and principal" Case Else Range("A1").Value = interest Range("A1").ColumnWidth = 15 Range("B1").Value = "is the interest that you requested" Range("A2").Value = sum Range("B2").Value = "is the sum of interest and principal" End Select inputFromUser = InputBox("Want to compute more? (y/n)", "User Input Window", "n") Loop While inputFromUser = "y" End Sub

Function CalcDelta(sigma As Double, K As Double, S As Double, currDate As Date, expDate As Date, r As Double, optionType As String) As Double Dim d1 As Double Dim t As Double t = (expDate - currDate) / d1 = (Log(S / K) + (r + sigma * sigma / 2) * t) / (sigma * t ^ (1 / 2)) If optionType = "Call" Then CalcDelta = Application.WorksheetFunction.Norm_S_Dist(d1, True) Exit Function End If If optionType = "Put" Then CalcDelta = (Application.WorksheetFunction.Norm_S_Dist(d1, True) - 1) Exit Function End If MsgBox "Option type not recognized" CalcDelta = 0 End Function

 Use the recorder to Download a Table from Alpha (you need to be on a lab Machine or on VPN)  Examine the code  Run the macro

 Use the recorder to execute some SQL (you need to be on a lab Machine or on VPN) Run in a command window (start > cmd) runas /netonly /user:”mcintire\your McIntire id” “the path to excel from C:“ runas /netonly /user:”mcintire\sg6m” “C:\Program Files (x86)\Microsoft Office\Office15/Excel.exe“  Examine the code and modify it Note: delete commandtype = 0  Run the macro

 Good for simple subs, but significant limitations (next)  Use it to find out commands Example: highlight a cell and change the name of a worksheet

 Cannot create loops  Cannot create If-Then statements  Cannot display pop-up messages or custom dialog boxes  Cannot create functions  Often produces overcomplex code

Sub Life() Dim lifeField As Range Set lifeField = Application.Worksheets("Sheet1").Range("B2:AL40") For i = 1 To 60 Range("A1") = i For Each c In lifeField counter = 0 If c.Offset(-1, -1).Interior.Color = vbRed Then counter = counter + 1 End If If c.Offset(-1, 0).Interior.Color = vbRed Then counter = counter + 1 End If If c.Offset(-1, 1).Interior.Color = vbRed Then counter = counter + 1 End If If c.Offset(0, -1).Interior.Color = vbRed Then counter = counter + 1 End If If c.Offset(0, 1).Interior.Color = vbRed Then counter = counter + 1 End If If c.Offset(1, -1).Interior.Color = vbRed Then counter = counter + 1 End If If c.Offset(1, 0).Interior.Color = vbRed Then counter = counter + 1 End If If c.Offset(1, 1).Interior.Color = vbRed Then counter = counter + 1 End If c.Value = counter Next If i <> 60 then For Each c In lifeField If c > 3 Or c < 2 Then c.Interior.Color = vbWhite End If If c = 3 Then c.Interior.Color = vbRed End If If WorksheetFunction.RandBetween(0, 1000) < 1 Then c.Interior.Color = vbRed End If Next End If Next End Sub