Saeed Ghanbartehrani Summer 2015 Lecture Notes #4: Working with Variables and User Interfaces IE 212: Computational Methods for Industrial Engineering.

Slides:



Advertisements
Similar presentations
Working with Intrinsic Controls and ActiveX Controls
Advertisements

ISOM3230 Business Applications Programming
PROGRAMMING IN VISUAL BASIC PART 1
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.
Using Visual Basic 6.0 to Create Web-Based Database Applications
String Variables Visual Basic for Applications 4.
Exploring Office Grauer and Barber 1 Creating More Powerful Applications: Introduction to VBA(Wk9)
1 Chapter 4 The Fundamentals of VBA, Macros, and Command Bars.
Input Validation Check the values entered into a text box before beginning any calculations Validation is a form of ‘self-protection’, rejecting bad data.
Data Types and Operations Programming Fundamentals (Writing Code)Programming Fundamentals (Writing Code)
To type the VB code behind the command button (named cmdPush), Double-Click on the Push Me (caption) command button As a result the Visual Basic Code Window.
Exploring Microsoft Excel 2002 Chapter 8 Chapter 8 Automating Repetitive Tasks: Macros and Visual Basic for Applications By Robert T. Grauer Maryann Barber.
Creating Embedded Formative Assessment Dr. Steve Broskoske Misericordia University EDU 533 Computer-based Education.
Spreadsheet-Based Decision Support Systems
Chapter 3: Using Variables and Constants
Programming with Microsoft Visual Basic th Edition CHAPTER THREE USING VARIABLES AND CONSTANTS.
IE 212: Computational Methods for Industrial Engineering
McGraw-Hill/Irwin Copyright © 2013 by The McGraw-Hill Companies, Inc. All rights reserved. Extended Learning Module M Programming in Excel with VBA.
University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-3 1 Lecture Outline Variable Scope Calling another subprogram Programming.
Tutorial 11 Using and Writing Visual Basic for Applications Code
1 Visual Basic for Applications (VBA) for Excel Prof. Yitzchak Rosenthal.
Copyright © 2008 Pearson Prentice Hall. All rights reserved. 1 Microsoft Office Excel Copyright © 2008 Pearson Prentice Hall. All rights reserved
Input, Output, and Processing
Outline Software and Programming Program Structure Tools for Designing Software Programming Languages Introduction to Visual Basic (VBA)
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.
Tutorial 51 Programming Structures Sequence - program instructions are processed, one after another, in the order in which they appear in the program Selection.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
Chapter 9 Macros And Visual Basic For Applications.
Overview of VBA Programming & Syntax. Programming With Objects u Objects –Properties: attributes or characteristics of an object (e.g., font size, color,
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Variables & Function Calls. Overview u Variables  Programmer Defined & Intrinsic  Data Types  Calculation issues u Using Functions  The val() function.
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.
1 Scripting Languages VBScript - Recognized mainly by Internet Explorer only - Netscape does have a plug-in JavaScript - Recognized by Internet Explorer.
Chapter 4 Variables and constants. 4.1 Variables -Use of variables is good programming style -easier to modify -easier for a programmer to understand.
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
Introduction to Excel VBA UNC Charlotte CPE/PDH Series December 17, 2009.
ME 142 Engineering Computation I Input, Output & Documentation.
ME 142 Engineering Computation I Using Subroutines Effectively.
Hungarian Notation A must in this course Every object used MUST be renamed including the form(s) using the following rules Form  frmFormName E.g. frmTemperature.
Programming with Microsoft Visual Basic th Edition
Tutorial 3: Using Variables and Constants1 Tutorial 3 Using Variables and Constants.
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.
Variables and Expressions Programming Right from the Start with Visual Basic.NET 1/e 7.
Controlling Program Flow with Decision Structures.
Microsoft Visual Basic 2012 CHAPTER FOUR Variables and Arithmetic Operations.
Visual Basic.NET Programming for the Rest of Us Keith Mulbery Utah Valley State College.
Creation of Variables with Numeric, alphanumeric, date, picture, memo data types Constant - A quantity that does not change during the execution of a program.
ME 142 Engineering Computation I Interacting with Spreadsheets.
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are used in programs so that values can be represented with.
Programming with Microsoft Visual Basic 2012 Chapter 3: Using Variables and Constants.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
IE 8580 Module 4: DIY Monte Carlo Simulation
A variable is a name for a value stored in memory.
VBA - Excel VBA is Visual Basic for Applications
Microsoft Office Illustrated
Variables and Arithmetic Operations
Exploring Microsoft Excel
WEB PROGRAMMING JavaScript.
Visual Basic Programming Chapter Four Notes Working with Variables, Constants, Data Types, and Expressions GROUPBOX CONTROL The _____________________________________.
T. Jumana Abu Shmais – AOU - Riyadh
CHAPTER FOUR VARIABLES AND CONSTANTS
Presentation transcript:

Saeed Ghanbartehrani Summer 2015 Lecture Notes #4: Working with Variables and User Interfaces IE 212: Computational Methods for Industrial Engineering

Overview of this Module  Data types in Excel VBA  Declaring variables –Scope of variables  Using the MsgBox and InputBox functions 2

Overview of this Module (cont.)  This module is accompanied by an Appendix that provides an introduction to the following topics –Conversion and string functions –Mathematical and trigonometric math functions  The material in the Appendix will not be covered during lecture –Students must review, test, and understand the functions included in the Appendix on their own 3

Data Types in Excel VBA 4  Engineers primarily use computers to manipulate numerical data –Integer and decimal values  However, engineers also deal with other forms of data –Logical  True  False –Alphanumeric  Names  Dates  etc.

Data Types in Excel VBA (cont.) 5  Excel VBA has two ways of dealing with data types –VBA can automatically decide the data type to assign to a variable  Pro o Requires less effort  Con o Translates into a lot of wasted computer memory –The user can explicitly specify the variable type  Translates into procedures that run more efficiently and programs that are easier to debug –In this course, you must always declare your variables EXPLICITLY

Forcing Explicit Variable Declaration 6  Windows OS –In the VBE, select Tools > Options… –Select the tab Editor (if it is not already selected) –Add a checkmark to the option “Require variable declaration”  Close and re-open Excel

Forcing Explicit Variable Declaration (cont.) 7  Mac OS –Open Excel and then select a new workbook –Click on the Developer tab –Click on the Editor icon –Click on the Excel menu option and select Preferences  You will see a checkbox labeled “Require Variable Declaration”  Check this option and press “OK”  Close and re-open Excel

Forcing Explicit Variable Declaration (cont.) 8  The action just executed will automatically add a special line of code at the top of all Excel VBA code windows –Option Explicit  Option Explicit must now appear at the top of all Modules in every homework assignment turned in

Data Types in Excel VBA 9  A data type categorizes the values that can be assigned to a variable –There are several different data types available in Excel VBA  The following Excel VBA data types are used most often –Integer  Long –Double  Single –String –Boolean –Range –Worksheets –Variant

Data Types in Excel VBA (cont.) 10  The table below shows the memory requirements in bytes (1 byte = 8 bits) for some of the most common Excel VBA data types Source:

Data Types in Excel VBA (cont.) 11  The justification for the many different data types is the trade off among –Calculation requirements  A variable is needed to store the total number of seconds in a 24-hr period. What data type should be used?  Variable type definition should be planned carefully so that program execution errors are avoided –Memory requirements  Variable data types that use more bytes require more computer memory –Processing time requirements  Excel VBA processes double-precision numbers more efficiently than single-precision numbers

Variable Declaration in Excel VBA 12  The statement Dim is used in Excel VBA to declare a variable –Dim variable As DataType  When naming variables, the variable name must: –Start with a letter –Contain only letters, numbers or the underscore (i.e., _) character –Be less than or equal to 255 characters in length –Not use special characters (e.g., !, ?, &) or blank spaces –Not be a keyword (e.g., Sub, End, True)  Pick a style to name your variables and be consistent

Variable Declaration in Excel VBA (cont.) 13  In Excel VBA, the type of each variable must be set individually  For example, assume that you would like to declare variables var1 and var2 as type Integer. Which statement should you use? a)Dim var1 As Integer, var2 As Integer b)Dim var1, var2 As Integer c)Both a) and b) will work

Variable Declaration in Excel VBA (cont.) 14  In Excel VBA, you can also define constant variables –Use the keyword Const to declare a constant variable  Const var_Name = Value  Const pi = –One a constant is declared, it cannot be modified or assigned a new value in the code

Integer and Double Data Types 15  Numerical values can be represented with both the Integer and Double data types  Type Integer –Non-decimal numbers that range in value from -32,768 to 32,767 –Used for simple numerical values, counting in loops, and enumerating arrays  Type Double –Negative range  E308 to E-324 –Positive range  E-324 to E308 –Useful when working with data that is non-integer and/or very large

String Data Type  A string is a segment of text and may include –Upper and lower-case letters –Punctuation marks –Numbers  Numbers assigned to a variable of type String cannot be used in calculations –They will be viewed as text  Strings are commonly used to name objects, label objects, and label data in spreadsheets 16

Boolean Data Type  A Boolean is a variable whose value is either True or False  Boolean variables will be used often in –Logic statements, –If…Then statements, and –Loops 17

Range Data Type  A variable of type Range inherits all the properties and methods of the Range object  The Set declaration statement must be used to initialize the value of a variable of type Range –For example, to set the variable MyRange equal to cell A1 we would type the following  Dim MyRange As Range.  Set MyRange = Range(“A1”) 18

Range Data Type (cont.)  Variables of type Range will be used often to increase the efficiency of Excel VBA code –A variable of type Range can be used to define a StartCell  The value of this range variable is set at the beginning of the code and then referenced throughout the remainder of the code  Variables of type Range can also be used to make Excel VBA code more dynamic –e.g., use an Input Box to capture where the user wants to start a table 19

Worksheet Data Type  The Worksheet data type defines a Worksheets object  A variable of type Worksheet inherits all the properties and methods of the Worksheets object –This object can be used when creating loops and/or functions to perform repeated methods or set repeated properties to multiple worksheets 20

Scope of Variables in Excel VBA  It is very important to understand the scope of each variable that is declared  An important program design step is to ask yourself the following questions –Will the variable be used only in this sub procedure? –Will the variable be used only in this function procedure?, or –Will the variable be used in several different procedures?  There are two Excel VBA keywords used to set the scope of a variable –Private –Public 21

Private Variables  A variable can be of scope Private on two levels –Module level  Variable can be used in any procedure in the module, but only in the particular module in which it was declared  Variable is created when the module starts, and then stays in existence until the module terminates  Use keyword Dim or Private in the variable declaration statement before the first procedure in the module –Procedure level  Variable can only be used in the particular procedure in which it was declared  Variable is created when the procedure starts, and then destroyed when the procedure terminates  Use keyword Dim in the variable declaration statement 22

Procedure Level vs. Module Level  Procedure level Private declaration Sub Sub1() Dim i As Integer..... End Sub Sub Sub2() Dim i As Integer.... End Sub 23  Module level Private declaration Dim (or Private) i As Integer Sub Sub1() End Sub Sub Sub2() End Sub

Public Variables  The Public declaration statement is used to declare the scope of a variable as public –The keyword Public can only be used at the module level  Public i As Integer  A variable with scope Public can be used in any sub procedure in any module –Also referred to as a Workbook or global variable 24

Keeping Track of Variable Values  There are two main ways to keep track of variable values while running (or debugging) an Excel VBA program –Use the Watch Window  Click on View > Watch Window from the menu  Select any variable from the Code Window and drag it to the Watch Window –Hold your cursor over a variable name in the Code Window to see a small display of its value 25

MsgBox and InputBox Functions  Message Boxes allow you to display messages to the user in a small dialog box  Input Boxes allow you to prompt the user to enter a value in a small dialog box 26

MsgBox Function  The following can be printed with the MsgBox function –Text –Variable values –You can concatenate text and variable values with the & character 27 MsgBox “This is a string of text.” MsgBox "The height is " & h & vbCrLf & _ " and the width is " & w & "."

MsgBox Function (cont.)  Button types and response types can be specified as part of the MsgBox function to make it more user-friendly –MsgBox (prompt, [buttons], [title], [helpfile, context])  MsgBox function arguments –The prompt is either text or a variable (or concatenation of both) which will be displayed in the dialog box –The title argument allows you to enter a title for the dialog box –The helpfile and context arguments allow you to give the user help options 28

MsgBox Function (cont.)  The buttons argument takes a VB Constant value to determine the number and style of buttons available to the user –vbOKOnly  Displays an OK button only –vbOKCancel  Displays OK and Cancel buttons –vbYesNoCancel  Displays Yes, No, and Cancel buttons –vbYesNo  Displays Yes and No buttons 29

MsgBox Function (cont.)  If the VBA program intends to capture which button is pressed by the user, then the arguments of the MsgBox function must be enclosed in parentheses –MsgBox function structure to display data only –MsgBox function structure to capture a user’s response (i.e., button pressed) 30 MsgBox "This is a message box to display information", _ vbCritical, "Please respond" response = MsgBox (“Do you want to continue?", _ vbYesNo, “User Input Required)

MsgBox Function (cont.)  The user’s response can be captured and assigned to a VBA variable of type integer –vbOK or 1  If response was OK –vbCancel or 2  If response was Cancel –vbAbort or 3  If response was Abort –vbRetry or 4  If response was Retry –vbIgnore or 5  If response was Ignore –vbYes or 6  If response was Yes –vbNo or 7  If response was No 31

InputBox Function  The InputBox function must always be assigned to a variable –The InputBox function returns a String containing the contents of the text box  The InputBox function general form is: –InputBox (prompt, [title], [default], [xpos], [ypos], [helpfile, context]) 32

InputBox Function (cont.)  InputBox function arguments –The prompt and title arguments of the InputBox function are the same as those of the MsgBox function –The default argument sets the default value to display in the InputBox –The xpos and ypos arguments set the position of the Input Box relative to the left and top edges of the screen –helpfile and context arguments (same as the MsgBox function) 33

InputBox Function (cont.)  For example, you may prompt the user to enter a number and store the user value in the variable UserNumber –UserNumber = InputBox (prompt, [title], [default], [xpos], [ypos], [helpfile, context]) 34

Summary  To declare a variable in VBA, use the command Dim  There are several data types available for variables in VBA, including Integer, Double, String, Booleans, Range, Worksheet, and Object  There are two types of scopes for variable declarations –Public –Private  Message Boxes and Input Boxes allow us to communicate with the user using VBA code 35