Modeling using VBA. Covered materials -Userforms -Controls -Module -Procedures & Functions -Variables -Scope.

Slides:



Advertisements
Similar presentations
Sep-05 Slide:1 VBA in Excel Walter Milner. Sep-05 Slide:2 VBA in Excel Introduction VBA = Visual Basic for Applications Enables end-user programming In.
Advertisements

1B40: Data analysis 1 Objects Visual Basic is an (OO) object-oriented language. Performing a task in Visual Basic (VB) or.
“Going loopy with Visual Basic!”
ISOM3230 Business Applications Programming
CP212 Midterm Review Original on Google Drive. *Omas Abdullah: My Life and the Oculus Rift* Featuring discussion of new age technologyused for gaming.
Excel and Visual Basic. Outline Data exchange between Excel and Visual Basic. Programming VB in Excel.
Object Oriented Programming A programming concept which views programs as objects with properties and ways to manipulate the object and the properties.
EXCEL VBA 101 Current Status Waiting Using Excel/VBA to Speed-up Daily Data Processing An Introduction to VBA Yongjun Chen Click Me to Start …
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.
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.
Arrays. What is an Array? An array is a way to structure multiple pieces of data of the same type and have them readily available for multiple operations.
1 Visual Basic Programming II Lecture 3 MIS233 Instructor – Larry Langellier.
Lecture Roger Sutton CO331 Visual Programming 12: One-dimensional Arrays 1.
VBA Modules, Functions, Variables, and Constants
VBA Programming Session #2. Things to Review  Variables  Procedures: Subs & Functions  If…Then  For…Next.
Arrays Array of Controls: several controls, of the same type (Class: a prototype for an object indicating the properties and methods), that have the same.
VBA & Excel Barry L. Nelson IEMS 465 Fall Quarter 2003.
ISAT 252 Introduction to Arrays. Should have read 2 Chapter 8 –pp , and pp
 Excel – Basic Elements  Using Macros  Excel VBA Basics  Excel VBA Advanced.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #3: Manipulating Excel Objects IE 212: Computational Methods for Industrial Engineering.
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.
Object Variables Visual Basic for Applications 3.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #4: Working with Variables and User Interfaces IE 212: Computational Methods for Industrial Engineering.
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.
Microsoft Visual Basic 2008 CHAPTER NINE Using Arrays and File Handling.
Microsoft Visual Basic 2005 CHAPTER 9 Using Arrays and File Handling.
Using Arrays and File Handling
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
259 Lecture 13 Spring 2013 Advanced Excel Topics – Arrays.
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.
Arrays and 2D Arrays.  A Variable Array stores a set of variables that each have the same name and are all of the same type.  Member/Element – variable.
© 1999, by Que Education and Training, Chapter 8, pages of Introduction to Computer Programming with Visual Basic 6: A Problem-Solving Approach.
Week 4.  Recap – Ranges  For Each Loops  Ranges Referencing Range Objects  Set (keyword)
Variables,Constants and Data types Variables temporarily stores values during the execution of an application Variables have a name and data type Declare.
‘Tirgul’ # 3 Enterprise Development Using Visual Basic 6.0 Autumn 2002 Tirgul #3.
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.
Overview of VBA Programming & Syntax. Programming With Objects u Objects –Properties: attributes or characteristics of an object (e.g., font size, color,
1 Working with Data Structures Kashef Mughal. 2 Chapter 5  Please review on your own  A few terms .NET Framework - programming model  CLR (Common.
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
ME 142 Engineering Computation I Using Subroutines Effectively.
# 1# 1 Using Procedures and Functions What is a procedure? What is a sub procedure (subroutine)? Built-in functions in your code What is a function? CS.
Lab 6 (2) Arrays ► Lab 5 (1) Exercise Review ► Array Concept ► Why Arrays? ► Array Declaration ► An Example of Array ► Exercise.
Introduction to Excel VBA UNC Charlotte CPE/PDH Series December 17, 2009.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley More About Array Processing 8.2 There Are Many Uses of Arrays and Many Programming.
Visual Basic Programming I 56:150 Information System Design.
Arrays and others. Annoucement Today’s office hour move to Friday 1:00PM to 3:00PM Today’s office hour move to Friday 1:00PM to 3:00PM Today Today  Call.
CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures.
Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.
CHAPTER 9 PART II. MULTIDIMENSIONAL ARRAYS Used to represent tables of values arranged in rows and columns. Table element requires two indexes: row and.
ME 142 Engineering Computation I Using Subroutines Effectively.
CN2180 Chapter 4 Kemtis Kunanuraksapong MSIS with Distinction, A+ MCTS, MCDST, MCP Kemtis Kunanuraksapong MSIS with Distinction, A+ MCTS, MCDST, MCP.
Lab 6 (1) Range Review, Control Logic and Loops ► Control Logic and Loops ► Exercise.
Controlling Program Flow with Decision Structures.
Visual Basic Review LBS 126. VB programming Project Form 1Form 2Form 3 Text boxButton Picture box Objects Text box Button Objects.
Arrays 1.
Programming Right from the Start with Visual Basic .NET 1/e
IE 8580 Module 4: DIY Monte Carlo Simulation
VBA - Excel VBA is Visual Basic for Applications
VBA - Excel VBA is Visual Basic for Applications
Visual Basic 6 (VB6) Data Types, And Operators
5. Using databases in VB.
Learning Excel Session 9 and 10 Dr. Chaitali Basu Mukherji.
EXCEL Creating An Array In VBA
Intro to Excel CSCI-150.
Presentation transcript:

Modeling using VBA

Covered materials -Userforms -Controls -Module -Procedures & Functions -Variables -Scope

Variant “ Data Type ” In VB you don ’ t have to declare variable before its usage – Then, VB will by itself declare such variable as “ Variant ” You can also declare variable as “ Variant ” – Dim myVar as Variant Variant – means that the variable may contain any data type

Variables Assignment To assign a value to a Numeric or String type Variable, you simply use your Variable name, followed by the equals sign (=) and then the String or Numeric To assign an Object to an Object type variable you must use the key word "Set"

Variables Assignment – cont. Sub ParseValue() Dim varName as String varName = “Cuong Do” Dim varAge as Integer varAge = “28” Dim varCell as Range Set varCell = Range("A1") varCell.Value = “123” End Sub

VBA Variables Scope & Lifecycle The scope & lifecycle of a variable defines the code where the variable can be accessed and time when the stored data is kept inside the variable Procedure-Level – Variables defined inside procedures – Can be accessed only inside the procedure and keep their data until the End statement of the procedure Module-Level – Defined in the top of a Module – Any procedure inside the Module can access the variable – The variable retains the values unless the Workbook closes Project-Level, Workbook Level, or Public Module-Level – Defined as “ Public ” in the top of a Module – Can be accesses by any procedure in any module – The variable retains the values unless the Workbook closes

VBA Variables Scope & Lifecycle – cont. Sub scopeExample() Dim x as Integer x = 5 End Sub Dim y as Integer ‘ all the module procedures are here … Public z as Integer ‘ all the module procedures are here … Procedure level variables Module level variables Project level variables

Which variable? Module1 Userform8

How to address public variables? Userform8 Module1

Basic Excel Classes Workbook: the class represents an Excel file Worksheet: represents a single worksheet Cell: represents a single cell

Excel Containers Workbooks: a collection of objects of class “ Workbook ” Worksheets: a collection of objects of class “ Worksheet ” Range: a range of objects of class Cell

Referring to Cells by Using a Range Object Sub Random() Dim myRange As Range Set myRange = Worksheets("Sheet1").Range("A1:D5") myRange.Formula = "=RAND()" myRange.Font.Bold = True End Sub

Referring to Cells by Using a Range Object Sub Test1() Range("A10").Value = "123" End Sub Sub Test2() Set varRange = Range("A10") varRange.Value = "123" End Sub Sub Test3() Worksheets(1).Range("A10") = "123" End Sub Sub Test4() Worksheets("Sheet1").Range("A10") = "123" End Sub Same outcome here

Referring to Multiple Ranges Sub ClearRanges() Worksheets("Sheet1")._ Range("C5:D9,G9:H16,B14:D18").ClearContents End Sub

Referring to Cells by Using Index Numbers Cells indexing format: – Cells(row, column), where both row and column are given as integers (starting from 1) – Cells(index) Sub EnterValue() Worksheets("Sheet1").Cells(6, 1).Value = 10 End Sub Sub EnterValue() Worksheets(1).Range("A1:D3").Cells(7).Value = "Here it is" End Sub

Referencing Cells Relative to Other Cells ActiveCell.Offset(1, 2).Value = "Here it is"

Some useful methods/properties of Excel Classes Workbooks.Close – closes the active workbook Workbooks.Count – returns the number of currently open workbooks Range( “ A1 ” ) is the same as Range( “ A1 ” ).Value Cells( 1,1 ) is the same as Cells( 1,1 ).Value Worksheets(1).Column( “ A:B ” ).AutoFit Worksheets(1).Range( “ A1:A10 ” ).Sort_ Workbooks.Open fileName:= “ test.xls ”

Arrays Dim Students(1 to 5) As String Students(1) = “Jack” Students(2) = “Nick”

Multidimensional Arrays Dim Grades(1 to 5,1 to 2) Grades(1,1)=“Jack” Grades(1,2)=“A” Grades(2,1)=“Nick” Grades(2,2)=“B” For i=1 to 2 MsgBox Grades(i,1) & “ got ” & Grades(i,2) Next MsgBox Grades(1, 1) & " got " & Grades(1, 2) & vbCrLf & _ Grades(2, 1) & " got " & Grades(2, 2)

Resizing the Arrays Dim Grades(1 to 5,1 to 2) Grades(1,1)=“Jack” Grades(1,2)=“A” Grades(2,1)=“Nick” Grades(2,2)=“B” ‘ Now ReDim the array ReDim Grades(1 to 10,1 to 2) ‘previous values won’t be kept ReDim Preserve Grades(1 to 10,1 to 2) ‘preserve previous values Only the first dimension can be changed!

Upper & Lower Index Bounds of an Array Dim A(3): index from 0 to 3 Dim A(1 to 3): index from 1 to 3 Dim A(1 To 100, 0 To 3, -3 To 4) – UBound(A, 1) – will return “ 100 ” – UBound(A, 2) – will return “ 3 ” – UBound(A, 3) – will return “ 4 ” – LBound(A, 1) – will return “ 1 ” – LBound(A, 2) – will return “ 0 ” – LBound(A, 3) – will return “ -3 ”

VBA Control Structures - If If Grade >= 90 Then MsgBox "You got an A" ElseIf Grade >= 80 Then MsgBox "You got a B" ElseIf Grade >= 70 Then MsgBox "You got a C" Else MsgBox "You are out of scope” End If Need to capture the rest of cases

VBA Control Structures – Select Select Case Grade Case Is >= 90 MsgBox "You got an A Case Is >= 80 MsgBox "You got an B” Case Is >= 70 MsgBox "You got a C” Case Else MsgBox "You out of scope” End Select Need to capture the rest of cases

VBA Control Structures – Loops Sub factorial1() Dim N N = 10 Cells(1, 1) = 1 For i = N To 1 Step -1 Cells(1, 1) = Cells(1, 1) * i Next End Sub Sub factorial3() Dim N N = 10 i = N Cells(1, 3) = 1 Do Cells(1, 3) = Cells(1, 3) * i i = i - 1 Loop While i >= 1 End Sub Sub factorial2() Dim N N = 10 i = N Cells(1, 2) = 1 Do While i >= 1 Cells(1, 2) = Cells(1, 2) * i i = i - 1 Loop End Sub N! Loop at least once

Loops for Collection Objects Sub WorkSheetsLoop() Dim mySheet As Worksheet For Each mySheet In Worksheets MsgBox mySheet.Name Next mySheet End Sub

Nested Loops Example Sub NestedLoopExample() For i = 1 To 5 For j = 1 To 5 Cells(i, j) = "Row " & i & " Col " & j Next j Next i End Sub

Worksheet functions Sub FuncExample() Range("D6") = Application. WorksheetFunction. Sum(Range("D1:D5")) ‘ Can also use Application. Sum for short End Sub ‘ Another way to get the sum Range("D6").Formula = "=SUM(D1:D5)"

Other Issues in VBA programming What if need to pass an array of arguments without knowing the number of arguments

Graphs

Private Sub cmdGenerate_Click() Range("B2:E13").Formula = "=RAND()*100" End Sub Private Sub cmdPlot_Click() Create_Chart_Sheet End Sub Sub Create_Chart_Sheet() Charts.Add With ActiveChart.ChartType = xlColumnClustered.SetSourceData Source:=Sheets("Sheet4").Range("B1:E13") End With End Sub

Graphs (Columnclusted)

Graphs (BarStacked)