Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 1 Visual Basic for Applications - VBA IE 484

2 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 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 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 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 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 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 8 If  If condition1 [And-Or condition2] Then u Statements1  [ElseIf u Statements2  ElseIf u Statements3  Else u Statements4]  End If

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

10 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 11 Other Loops  Do Until condition ...  Loop  Do ...  Loop Until condition --------------------------------------------------------------------------------------  Do While condition ...  Loop  Do ...  Loop While condition

12 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 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: www.frontsys.com/mlvbaref.htm (solver.com)www.frontsys.com/mlvbaref.htm  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 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 15 Cancel Button  Code for the Cancel button on user forms: Private Sub CancelButton_Click() Unload Me End End Sub

16 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 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 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 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 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 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 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 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. http://support.microsoft.com/?kbid=129796

24 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 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 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(...;...;...;...).


Download ppt "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."

Similar presentations


Ads by Google