 Excel – Basic Elements  Using Macros  Excel VBA Basics  Excel VBA Advanced.

Slides:



Advertisements
Similar presentations
1 VBA Introduction. Basic Components 2 VBA LANGUAGE OFFICE OBJECTS EXCEL OBJECTS ACCESS OBJECTS WORD OBJECTS OUTLOOK OBJECTS POWERPOINT OBJECTS.
Advertisements

ISOM3230 Business Applications Programming
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.
Modeling using VBA. Covered materials -Userforms -Controls -Module -Procedures & Functions -Variables -Scope.
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.
Visual Basic for Applications IntroductionIntroduction The Control ToolboxThe Control Toolbox View ► Toolboxs ► Control Toolbox Command ButtonsCommand.
Some computer fundamentals and jargon Memory: Basic element is a bit – value = 0 or 1 Collection of “n” bits is a “byte” Collection of several bytes is.
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.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
VBA Modules, Functions, Variables, and Constants
String Variables Visual Basic for Applications 4.
VBA Programming Session #2. Things to Review  Variables  Procedures: Subs & Functions  If…Then  For…Next.
Modeling using VBA. Using Toolbox This is a label This is a button Using the Toolbox select a GUI element and by mouse-click place it on the frame This.
Visual Basic: An Object Oriented Approach 4: Simple Programming in VB.
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.
IE 212: Computational Methods for Industrial Engineering
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.
Introduction on VBA Lab 05 ins.Tahani Al_dweesh. Lab Objectives Introduction Calculation with VBA Storing and Retrieving Variables in a Worksheet Using.
Microsoft Visual Basic 2008 CHAPTER NINE Using Arrays and File Handling.
Microsoft Visual Basic 2005 CHAPTER 9 Using Arrays and File Handling.
1 VBA – podstawowe reguły języka Opracowanie Janusz Górczyński wg Microsoft Help.
1 Visual Basic for Applications (VBA) for Excel Prof. Yitzchak Rosenthal.
Using Arrays and File Handling
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.
Date Variables Visual Basic for Applications 5. Objectives n In this tutorial, you will learn how to: n Reserve a Date variable n Use an assignment statement.
MS Visual Basic Applications Walter Milner. Event-driven programming Standard approach for GUIs Contrast with old character interfaces – program determines.
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,
Week 6.  Assessment 2  Do Loops  Custom Functions.
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
1 CS105 Discussion 5 – Variables and If Announcements MP 1 due on Monday Midterm 1 on Tuesday If you need a conflict, request it NOW!!
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.
Types of Visual Basic Data Numeric Data Non Numeric Data.
Introduction to Excel VBA UNC Charlotte CPE/PDH Series December 17, 2009.
Visual Basic Programming I 56:150 Information System Design.
CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures.
ME 142 Engineering Computation I Using Subroutines Effectively.
# 1# 1 What is a variable that you create? What is a constant that you create? What is an intrinsic (built-in) constant? What variables are built in?
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.
Visual Basic Review LBS 126. VB programming Project Form 1Form 2Form 3 Text boxButton Picture box Objects Text box Button Objects.
Creation of Variables with Numeric, alphanumeric, date, picture, memo data types Constant - A quantity that does not change during the execution of a program.
More on Variables and Subroutines. Introduction Discussion so far has dealt with self- contained subs. Subs can call other subs or functions. A module.
Financial Information Management VB, VBA, VS, VSTO & VBE: Putting it all together Source: Excel VBA Programming by John Walkenbach.
Lab 5 Arrays ► Lab 4 Exercise Review ► Array Concept ► Why Arrays? ► Array Declaration ► An Example of Array ► Exercise.
Excel VBA – Creating Function Procedures Dr Joanna Wyrobek 1.
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.
2. Understanding VB Variables
Learning Excel Session 9 and 10 Dr. Chaitali Basu Mukherji.
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
CS285 Introduction - Visual Basic
Presentation transcript:

 Excel – Basic Elements  Using Macros  Excel VBA Basics  Excel VBA Advanced

 Module – collection of logically related procedures grouped together  Procedure – a group of ordered statements enclosed by Sub and End Sub  Function – the same as a procedure, but also returns some value and is closed between Function and End Function key words

Sub ShowTime() Range("C1") = Now() End Sub Function sumNo(x, y) sumNo = x + y End Function The procedure places the current time inside cell C1 The function returns sum of two input numbers, whose values are in the parameter variables x & y

Sub z(a) MsgBox a End Sub Sub x() Call z("ABC") End Sub Sub y() z "ABC “ End Sub Sub ShowSum() MsgBox _ Module1.sumNo(3,5) End Sub Function sumNo(x, y) sumNo = x + y End Function If there are few sumNo functions, the full name of the function is needed

 Passing arguments by reference –  Is the VBA default  Means, if any changes happened to the argument variables, they will be preserved after the function/procedure finishes  Passing arguments by value –  Is possible in VBA (by explicit definition)  Means, the pre-calling state of the argument variables will be preserved after the procedure/function finishes

Sub TestPassing1() Dim y As Integer y = 50 AddNo1 y MsgBox y AddNo2 y MsgBox y End Sub Sub AddNo1(ByRef x As Integer) x = x + 10 End Sub Sub AddNo2(x As Integer) x = x + 10 End Sub public Sub TestPassing2() Dim y As Integer y = 50 AddNo3 y MsgBox y End Sub private Sub AddNo3(ByVal x _ As Integer) x = x + 10 End Sub

 Use public to allow any module to call the function/procedure  Use private to make limited access to the function/procedure (only from the owning module)

 A variable is used to store temporary information within a Procedure, Module …  A variable name  Must start with letter and can ’ t contain spaces and special characters (such as “ & ”, “ % ”, “ \ ” )  Can ’ t be any excel keyword ( “ if ”, “ while ”… )  Can ’ t have identical name to any existing class ( “ Wroksheet ”, “ Workbook ”… )

 Byte – positive integer numbers (0:255)  Integer – integers (-32,768 : 32,767)  Long – 4-byte integer  Currency – for fixed-point calculations  Single – 2-byte floating-point numbers

 Double – double-precision floating-point numbers  Date – used to store dates and times as real numbers.  String – contains a sequence of characters

Sub NoVariable() Range("A1").Value = _ Range("B2").Value Range("A2").Value = _ Range("B2").Value * 2 Range("A3").Value = _ Range("B2").Value * 4 Range("B2").Value = _ Range("B2").Value * 5 End Sub Sub WithVariable() Dim _ iValue as Integer iValue = _ Range("B2").Value Range("A1").Value = _ iValue Range("A2").Value = _ iValue * 2 Range("A3").Value = _ iValue * 4 Range("B2").Value = _ iValue * 5 End Sub In VB the end of statement is in the end of line. To write the same statement in few lines use “ _ ” at the end of line!

 Declaring Variables  Format: Dim varibaleName AS dataType  Examples:  Dim myText As String  Dim myNum As Integer  Dim myObj As Range  The default value of  any numeric variable is zero  any string variable – “” (empty string)  an Object variable – is nothing (still the declaration will store space for the object!!!)

 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  The price is very high!!! – any time VB access such variable, it will spend time on “ deciding ” what is its “ current ” type!

 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"

Sub ParseValue() Dim sWord as String Dim iNumber as Integer Dim rCell as Range Set rCell = Range("A1") sWord = Range("A1").Text iNumber = Range("A1").Value End Sub

 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

 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

 Workbook: the class represents an Excel file  Worksheet: represents a single worksheet  Sheet: represents a single worksheet or chartsheet  Cell: represents a single cell

A current Worksheet A Range C4:D7 A Cell A Current Workbook

 Workbooks: a collection of objects of class “ Workbook ”  Worksheets: a collection of objects of class “ Worksheet ”  Sheets: a collection of Sheet objects  Range: a range of objects of class Cell

Sub Test1() Worksheets("Sheet1").Range("A10", "B12") = "Hello “ Worksheets(1).Range("A13,B14") = "World!" End Sub This will take the whole square between the two cells The range of two cells Two equal ways to refer Sheet1

Which Workbook was Used?

Sub ShowWorkSheets() Dim mySheet As Worksheet For Each mySheet In Worksheets MsgBox mySheet.Name Next mySheet End Sub

How many times the user will click on the button?

 Cells indexing format:  Cells(row, column), where both row and column are given as integers (starting from 1)  Cells(index) – see the next slide  Following expressions are equivalent and refer to the cell A1 in the currently active sheet:  ActiveSheet.Range.Cells(1,1)  Range.Cells(1,1)  Cells(1,1)

Range( “ B1:F5 ” ).Cells(12) = “ XYZ ” See how we calculate cell 12 In the given range!

ActiveCell.Offset(4, 5) = 1 This is the currently active cell The assignment result

 Workbooks.Close – closes the active workbook  Workbooks.Count – returns the number of currently open workbooks  Range( “ A1 ” ) is the same as Range( “ A1 ” ).Value  Worksheets(1).Column( “ A:B ” ).AutoFit  Worksheets(1).Range( “ A1:A10 ” ).Sort_  Workbooks.Open fileName:= “ Hello.xls ”, password:= “ kukuriku ”

Dim myRange as Range Set myRange = Range( “ A1:A10 ” )

 Suppose, we want to keep a collection of all the books that we loan,  Or we want to keep lists of tasks for all the days of the week  The na ï ve solution is to keep a lot of variables  Another solution is to create array keeping the whole collection together

Dim LoanBooks(3) LoanBooks(1) = “ Winnie The Pooh ” LoanBooks(2) = “ Adventures of Huckleberry Finn ” LoanBook(3) = “ Frankenstein ” The array declaration. The size must be defined here!

Dim WeekTasks(7,2) WeekTasks(1,1) = “ To buy milk ” WeekTasks(7,1) = “ To dance ” … MsgBox WeekTasks(1,1) & ” ” & WeekTasks(1,2) _ & vbCrLf & WeekTasks(2,1) … What will the code print?

 There are two ways to resize the existing array:  ReDim LoanBooks(7) – will erase the old values  ReDim Preserve LoanBooks(7) – will preserve values in indexes 1-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 ”  Write code calculating the size of each one of the sub-arrays

 If Age >= 18 Then Status = "Adult" End If  If Age >=18 Then Status = “ Adult ” Vote = “ Yes ” Else Status = “ Child ” Vote = “ No ” End If

 If Age >= 18 Then MsgBox "You can vote" ElseIf Age >=22 and Age < 62 Then MsgBox “ You can drive ” End If

 Select Case Grade Case Is >= 90 LetterGrade = "A" Case Is >= 80 LetterGrade = "B" Case Is >= 70 LetterGrade = "C" Case Is >= 60 LetterGrade = "D" Case Else LetterGrade = “ E" End Select

For i = 10 to 1 Step -2 Cells(i, 1) = “ AB ” Next i i = 1 Do While i =< 10 Cells(i, 1) = i i = i + 1 Loop i = 1 Do Cells(i, 1) = i i = i + 1 Loop While i < 11

Sub CellsExample() For i = 1 To 5 For j = 1 To 5 Cells(i, j) = "Row " & i & " Col " & j Next j Next i End Sub