1 Visual Basic for Applications - VBA IE 484. 2 2 What is VBA?  VBA comes with Office u Objects (e.g. of Excel) are exposed for use by VBA u Visual Basic.

Slides:



Advertisements
Similar presentations
Using VB with MS Applications R. Juhl, Delta College.
Advertisements

ISOM3230 Business Applications Programming
Decision Analysis Tools in Excel
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.
Using Macros and Visual Basic for Applications (VBA) with Excel
Tutorial 7: Developing an Excel Application
Developing an Excel Application
Tutorial 8: Developing an Excel Application
XP New Perspectives on Microsoft Excel 2003, Second Edition- Tutorial 8 1 Microsoft Office Excel 2003 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.
Templates and Styles Excel Advanced. Templates are pre- designed and formatted spreadsheets –They provide consistency of layout/structure –They.
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
Excel and VBA Creating an Excel Application
Project 7 Forecasting Values With What-If Analysis: Using Data Tables, Scenarios, Goal Seek, and Solver Jason C. H. Chen, Ph.D. Professor of Management.
Customizing Word Microsoft Office Word 2007 Illustrated Complete.
Macros Tutorial Week 20. Objectives By the end of this tutorial you should understand how to: Create macros Assign macros to events Associate macros with.
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.
Lab 8 Solver In VBA ► Review – Solver Add-in In Excel ► Solver Add-in In VBA.
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.
Microsoft Excel 2007 © Wiley Publishing All Rights Reserved. The L Line The Express Line to Learning L Line.
VBA (Visual Basic for Applications) What is Excel, just a spreadsheet? Time for Demos...
© 2008 The McGraw-Hill Companies, Inc. All rights reserved. WORD 2007 M I C R O S O F T ® THE PROFESSIONAL APPROACH S E R I E S Lesson 22 Macros.
Copyright 2007, Paradigm Publishing Inc. EXCEL 2007 Chapter 7 BACKNEXTEND 7-1 LINKS TO OBJECTIVES Record & run a macro Record & run a macro Save as a macro-
Microsoft Excel Macros & Excel Solver (IENG490)
Enhancing User Interaction Through Programming
Ch 11: Userforms CP212 Winter Topics Designing User Forms o Controls Setting Properties o Tab Order o Testing Writing Event Handlers o Userform_Initialize.
Introduction to VBA MGMI Aug What is VBA? VBA = Visual Basic for Application Excel’s powerful built-in programming language An event-driven.
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.
PMS /134/182 HEX 0886B6 PMS /39/80 HEX 5E2750 PMS /168/180 HEX 00A8B4 PMS /190/40 HEX 66CC33 By Adrian Gardener Date 9 July 2012.
 An object-oriented programming language ◦ Instructions for the manipulation of objects ◦ A structured way to provide instructions to Excel  Excel has.
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.
Visual Basic for Applications Macro Programming For Microsoft Office.
OCC Network Drives  H:\  P:\ 
Chapter 19: The Solver Re-Visited Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Goal Seek and Solver. Goal seeking helps you n Find a specific value for a target cell by adjusting the value of one other cell whose value is allowed.
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.
Decision Making Using Excel
ME 142 Engineering Computation I Using Subroutines Effectively.
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.
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
Introduction to Excel VBA UNC Charlotte CPE/PDH Series December 17, 2009.
Introduction to Microsoft Excel Macros COE 201- Computer Proficiency.
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.
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.
McGraw-Hill/Irwin The Interactive Computing Series © 2002 The McGraw-Hill Companies, Inc. All rights reserved. Microsoft Excel 2002 Using Macros Lesson.
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
Outline In this module, the following topics will be covered:
VBA - Excel VBA is Visual Basic for Applications
VBA - Excel VBA is Visual Basic for Applications
VBA (Visual Basic for Applications) What is Excel, just a spreadsheet?
Microsoft Office Illustrated
Excel VBA Day 3 of 3 Tom Vorves.
Exploring Microsoft Excel
Microsoft Excel 2007 – Level 2
Presentation transcript:

1 Visual Basic for Applications - VBA IE 484

2 2 What is VBA?  VBA comes with Office u Objects (e.g. of Excel) are exposed for use by VBA u Visual Basic (not VBA) is a standalone software development package that you can run separately  It has typical programming elements such as looping, logical constructions, etc.  It can manipulate objects of application software packages (such as Excel) programmatically u You can use VBA to develop applications for these packages

3 3 Objects  Objects: Things you work with (e.g. in Excel) u Collections of objects are also an object (collection objects)  Worksheets object is a collection of Worksheet objects.  Properties: Attributes of an object (size, color, etc.)  Methods: Things you can do to an object (copy, paste, etc.). Methods may have arguments to indicate how a method is carried out, to provide input,...

4 4 Excel Object Hierarchy  Workbooks (Workbook) u Worksheets (Worksheet)  Ranges (Range) Name Style u Charts (Chart) u Windows (Window) u Styles (Style)  Font  Borders (Border)  Workbooks(“Sales”).Worksheets(“March”).Range(“ Istanbul”)

5 5 The Visual Basic Editor (VBE)  Tools->Macro->Visual Basic Editor u Alt-F11  You write your code in the Code window to the right  Your program consists of subs (subroutines, macros, procedures) and functions for different tasks u Functions return something (and one thing). Subs don’t return anything but you can send several variables into a sub and get their values changed.  You use variables of different types in your coding u String, u Integer u Long u Boolean u Single u Double u Currency u Variant u Object u Range  Declare your variables at the beginning of each sub using the keyword Dim u Dim i As Integer u Option Explicit forces you to declare all variables

6 6 Built-in  Built-in VBA functions u InputBox u MsgBox  & for concatenation MsgBox “The revenue is ” & revenue  Built-in VBA objects u ActiveWorkbook u ActiveSheet

7 7 Specifying Methods  Range(“A1”).Value (e.g. when you print) u Range(“A1”).Value = “Sales for March”  Range(“A1”).ClearContents  Range(“A1:B10”).Copy Destination := Range(“D1:E10”)

8 8 If  If condition1 [And-Or condition2] Then u Statements1  [ElseIf u Statements2  ElseIf u Statements3  Else u Statements4]  End If

9 9 Case  Select Case variable u Case value1  Statements1 u Case value2  Statements2 u Case Else  Statements  End Select

10 For  For i = 1 To 500 ...  Next  Dim cell As Range  For Each cell in Range(“Sales”) u With cell u... u End With  Next  General format:  Dim itm As Object  For Each itm in Collection ...  Next

11 Other Loops  Do Until condition ...  Loop  Do ...  Loop Until condition  Do While condition ...  Loop  Do ...  Loop While condition

12 Arrays  Dim Employee() As String  NEmployees = InputBox(“How many employees?”)  Redim Employee(NEmployees) u Redim deletes previous contents  Redim Preserve Employee(NEmployees)  This is called dynamic memory allocation. u If you know the number of elements your array will contain, you can declare the size from the start.  Dim Employee(10) As String  By default, indexing of arrays starts from 0! u If you want your arrays to be 1-based you need the following line at the top of each module.  Option Base 1

13 Solver  Solver add-in u Tools->Solver  If Solver option does not show, Tools->Add-Ins and then add!  Developed by a third-party  For help: (solver.com)  All Solver functions begin with the word Solver u SolverReset, SolverOk, SolverAdd, SolverOptions, SolverSolve,...  Solver bug! u In models with varying size with integer constraints such constraints are ignored  Repeat the the SolverReset and SolverOK lines SolverReset SolverOK... SolverReset SolverOK...

14 User Forms  User forms (dialog boxes) u For customized input, entry of user preferences, parameters, etc. u Insert -> UserForm u Using the Control Box you can insert several controls (textbox, label, radio button, list,...) to the user form.

15 Cancel Button  Code for the Cancel button on user forms: Private Sub CancelButton_Click() Unload Me End End Sub

16 Formatting - Example  With ActiveWorkbook.Worksheets(“Sheet1”).Range(“A1”) u.Font.Bold = True u.Font.Size = 14 u.Font.Name = “Garamond” u.Font.Italic = True u.Font.ColorIndex = 5 u.HorizontalAlignment = xlLeft u.Interior.ColorIndex = 37 u.InsertIndent 1 u.NumberFormat = “$#,##0”  End With

17 Excel Functions  You can also use existing Excel functions u No need to code their functionality on your own.  Example: u Dim myRange as Object u Set myRange = Sheets(“Sheet1”).Range(Cells(1, 10), Cells(10, 10)) u Application.WorksheetFunction.min(myRange)

18 Controlling Excel Behavior  Excel has some default settings. Some of them such as the flickering effect of the screen when it is refreshed frequently are very annoying when you run your macros.  Normally you turn the unwanted settings off at the beginning of the code. u When you are finished you reset them to their original values.  Examples: u Application.ErrorCheckingOptions.NumberAsText = False u Application.ScreenUpdating = False u Application.DisplayAlerts = False

19 Recording Macros  To record a macro do the following: u In Excel choose Tools->Macro->Record New Macro u Give a name, say myMacro to your macro on the window that pops up  You can also define a shortcut key  Press OK u Do whatever you want to do repetitively with different data in Excel, e.g.  Choose a column  Sort the column decreasingly u Stop recording by Tools->Macro->Stop Recording  Now whenever you run your macro the same actions you recorded will be executed. u Call myMacro u Tools->Macro->Macros->Run  Recording macros also help you to figure out the code for certain tasks you want to achieve but do not know how to do via VBA. Just record a macro, and copy the code you need to your own program.

20 Reference: Solver Messages - Results  0: Solver found a solution. All constraints and optimality conditions are satisfied.  1: Solver has converged to the current solution. All constraints are satisfied.  2: Solver cannot improve the current solution. All constraints are satisfied.  3: Stop chosen when the maximum iteration limit was reached.  4: The Set Target Cell values do not converge.  5: Solver could not find a feasible solution.  6: Solver stopped at user's request.  7: The conditions for Assume Linear Model are not satisfied.  8: The problem is too large for Solver to handle.  9: Solver encountered an error value in a target or constraint cell.  10: Stop chosen when the maximum time limit was reached.  11: There is not enough memory available to solve the problem.  12: Another Excel instance is using SOLVER.DLL. Try again later.  13: Error in model. Please verify that all cells and constraints are valid.

21 Reference: Solver Messages - Runtime  Problem to solve not specified: This message appears if you click Solve and you have not specified any adjustable cells in the By Changing Cells edit box, or if you have specified neither an objective in the Set Cell box nor any constraints. Without these elements, the problem definition is incomplete and the Solver cannot work with it.  Solver paused, current solution values displayed on worksheet: This message appears in the Show Trial Solution dialog box (i) on every iteration or Trial Solution, if you have checked the Show Iteration Results box in the Solver Options dialog, or (ii) when you press ESC to interrupt the solution process. You can click on Continue to proceed with the solution process, or click on Stop to stop the process and display the Solver Results dialog box. You can also save the current values of the decision variables in a scenario.  The maximum iteration limit was reached; continue anyway? This message appears in the Show Trial Solution dialog box when the Solver has completed the maximum number of iterations allowed in the Iterations box in the Solver Options dialog. The actions you can take are the same as those described under "Solver paused" above.  The maximum time limit was reached; continue anyway? This message appears in the Show Trial Solution dialog box when the the Solver has run for the maximum time (number of seconds) allowed in the Max Time box in the Solver Options dialog. The actions you can take are the same as those described under "Solver paused" above.  The Scenario Manager Changing Cells (...) do not include all the Solver Changing Cells. Only the Scenario Manager cell values will be saved. This message appears when you attempt to save the current values of the decision variables (adjustable or changing cells) in a scenario, using the Scenario button in the Show Trial Solution or Solver Results dialogs. If you have previously used the Scenario Manager to define scenarios where the Scenario Manager's changing cells do not include all of the Solver's changing cells, you will receive this message. If you want to save all of the decision variable values in a scenario, you'll have to first modify the Scenario Manager's changing cells (using Tools Scenarios...) and then re-run the Solver.

22 Reference: Solver Messages - Runtime  An unexpected internal error occurred, or available memory was exhausted: Incorporate the following line into your code before running the Solver: u Application.Run “Solver.xla!Auto_Open”

23 Reference: Calling Other Software  To run LINGO from Excel, check LINGO manuals.  To run your own program such as one written in C from Excel, there are several approaches. u Create a dll (dynamic link library) and declare the function (the entry point of your program) in your code and make a call to it  Declare Sub mySub Lib “C:\...\myDll.dll” Alias “mySub” (ByVal myLong As Long, myArray() As Double)  Call mySub(myLong, myArray) u Create the executable file (.exe) and make a call in VBA to run the executable  Call Shell(“....exe”, 1) Runs asynchronously, i.e. code does not wait for the executable to finish  If you want to wait for the executable to finish so that you can use the results of the executable in your reports, etc., there is a pretty complicated code available from Microsoft support which you can simply copy and paste.

24 Reference: DOS Command Prompt  Example: Run GAMS from command prompt using VBA code (assumes GAMS files are available under a folder called GAMS) gmsPath = ThisWorkbook.Path & "\GAMS" retVal = Shell("C:\WINDOWS\System32\cmd.exe /k cd " & gmsPath & " && gams coursop lo=1", 1)  Multiple commands are run via && u Check MS website for other cmd options.  /k option lets the window stay open after execution. u /c closes the window.

25 Reference: Changing Macro Security Level in Excel 2007  You can change macro security settings in the Trust Center, unless a system administrator in your organization has changed the default settings to prevent you from changing the settings. 1. On the Developer tab, in the Code group, click Macro Security. 2. In the Macro Settings category, under Macro Settings, click the option that you want. u Tip If the Developer tab is not displayed, click the Microsoft Office Button, click Excel Options, and then in the Popular category, under Top options for working with Excel, click Show Developer tab in the Ribbon.  Another Way: You can also access the Trust Center in the Excel Options dialog box. Click the Microsoft Office Button, and then click Excel Options. In the Trust Center category, click Trust Center Settings, and then click the Macro Settings category.  Note Any changes that you make in the Macro Settings category in Excel apply only to Excel and do not affect any other Microsoft Office program.

26 Reference: User Defined Functions (UDFs) Below UDF takes four (Double) arguments and returns the EOQ amount as Double. Public Function EOQ(demand As Double, setupCost As Double, holdingCost As Double, unitCost As Double) As Double EOQ = Sqr(2*demand*setupCost/holdingCost/unitCost) End Function  Place the function into a Module. u Open VBA Editor (Alt+F11) u Insert a module u Place the code into the module  You can now use the function in the Excel worksheet in any cell by typing =EOQ(...;...;...;...).