Visual Basic - Modules and Procedures



Similar documents
VB.NET Programming Fundamentals

One Dimension Array: Declaring a fixed-array, if array-name is the name of an array

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

RIT Installation Instructions

Visual Basic Programming. An Introduction

Creating Basic Excel Formulas

Creating Applications using Excel Macros/Visual Basic for Applications (VBA)

1. a procedure that you perform frequently. 2. Create a command. 3. Create a new. 4. Create custom for Excel.

Connecting to an Excel Workbook with ADO

Introducing VBA Message Boxes

Visual Basic: Objects and collections

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

Introduction. Syntax Statements. Colon : Line Continuation _ Conditions. If Then Else End If 1. block form syntax 2. One-Line syntax. Do...

13 Classes & Objects with Constructors/Destructors

Using Loops to Repeat Code

Excel & Visual Basic for Applications (VBA)

OpenOffice.org 3.2 BASIC Guide

Sources: On the Web: Slides will be available on:

Hands-on Exercise 1: VBA Coding Basics

EXAMPLE WITH NO NAME EXAMPLE WITH A NAME

Many applications consist of one or more classes, each containing one or more methods. If you become part of a development team in industry, you may

Formulas & Functions in Microsoft Excel

DATA 301 Introduction to Data Analytics Microsoft Excel VBA. Dr. Ramon Lawrence University of British Columbia Okanagan

To add a data form to excel - you need to have the insert form table active - to make it active and add it to excel do the following:

PL / SQL Basics. Chapter 3

Lesson 4.3: Using the VLOOKUP Function

PULSE Automation programming in Visual Basic. From BK training lectures arranged by Jiří Tůma & Radovan Zadražil

3 What s New in Excel 2007

MICROSOFT EXCEL FORMULAS

MAS 500 Intelligence Tips and Tricks Booklet Vol. 1

Like any function, the UDF can be as simple or as complex as you want. Let's start with an easy one...

How to Excel with CUFS Part 2 Excel 2010

2015 County Auditors Institute. May Excel Workshop Tips. Working Smarter, Not Harder. by David Scott,

Exercise 1: Python Language Basics

Unleashing Hidden Powers of Inventor with the API Part 1. Getting Started with Inventor VBA Hello Inventor!

USC Marshall School of Business Marshall Information Services

Creating Cost Recovery Layouts

with VBA

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

Construction Administrators Work Smart with Excel Programming and Functions. OTEC 2014 Session 78 Robert Henry

Excel 2007 Basic knowledge

Advanced Excel 10/20/2011 1

The Center for Teaching, Learning, & Technology

CIS300 - Study Guide for Test 3

ACS Microcomputer Workshop Excel: Functions and Data Analysis Tools

PRI-(BASIC2) Preliminary Reference Information Mod date 3. Jun. 2015

How To Use Excel With A Calculator

Differences in Use between Calc and Excel

Excel & Visual Basic for Applications (VBA)

Tips and Tricks SAGE ACCPAC INTELLIGENCE

Chapter 5 Names, Bindings, Type Checking, and Scopes

Using the For Each Statement to 'loop' through the elements of an Array

Move between open workbooks. Display the print menu. Select whole spreadsheet. Microsoft Excel Keyboard Keys. General

P R E M I E R. Microsoft Excel 2007 VBA (Macros) Premier Training Limited 4 Ravey Street London EC2A 4QP Telephone +44 (0)

Q&As: Microsoft Excel 2013: Chapter 2

Module 2 - Multiplication Table - Part 1-1

MATLAB Programming. Problem 1: Sequential

Simulation Tools. Python for MATLAB Users I. Claus Führer. Automn Claus Führer Simulation Tools Automn / 65

Microsoft Excel 2010 Part 3: Advanced Excel

Program to solve first and second degree equations

Name = array(x,y,...,z) the indexing starts at zero, i.e. Name(0) = x. Programming Excel/VBA Part II (A.Fring)

Guide to Performance and Tuning: Query Performance and Sampled Selectivity

Moving from C++ to VBA

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Performing Simple Calculations Using the Status Bar

Final Exam Review: VBA

Classroom Tips and Techniques: The Student Precalculus Package - Commands and Tutors. Content of the Precalculus Subpackage

ECDL. European Computer Driving Licence. Spreadsheet Software BCS ITQ Level 2. Syllabus Version 5.0

A Comparison of SAS versus Microsoft Excel and Access s Inbuilt VBA Functionality Jozef Tarrant, Amadeus Software Ltd., Oxford, UK

3.GETTING STARTED WITH ORACLE8i

Excel: Introduction to Formulas

How-To Guide. SigCard1 (With Microsoft Access) Demo. Copyright Topaz Systems Inc. All rights reserved.

Microsoft Excel 2010 Tutorial

Excel Intermediate. Table of Contents UPPER, LOWER, PROPER AND TRIM...28

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

National Database System (NDS-32) Macro Programming Standards For Microsoft Word Annex - 8

Financial Data Access with SQL, Excel & VBA

How To Create A Checkbox In Visual Basic (For A Powerpoint) With A Check Box At Run Time

Moving from CS 61A Scheme to CS 61B Java

Excel & Visual Basic for Applications (VBA)

Using Parametric Equations in SolidWorks, Example 1

Getting Started. Tutorial RIT API

Paper An Introduction to SAS PROC SQL Timothy J Harrington, Venturi Partners Consulting, Waukegan, Illinois

Excel 2003 Tutorials - Video File Attributes

Simply Accounting Intelligence Tips and Tricks Booklet Vol. 1

Formulas & Functions in Microsoft Excel

Chapter One Introduction to Programming

Formulas, Functions and Charts

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Java CPD (I) Frans Coenen Department of Computer Science

Add an Audit Trail to your Access Database

Departmental Reporting in Microsoft Excel for Sage 50 Accounts

VB.NET INTERVIEW QUESTIONS

Excel for Mac Text Functions

Keil C51 Cross Compiler

Commonly Used Excel Formulas

This chapter is completely devoid of any hands-on training material. It

SPSS INSTRUCTION CHAPTER 1

Excel Formatting: Best Practices in Financial Models

Using Casio Graphics Calculators

Transcription:

Visual Basic - Modules and Procedures Introduction A procedure is a unit of code enclosed either between the Sub and statements or between the Function and statements. A procedure should accomplish a simple well-defined task. Modules are workbook sheets that contain code. Each module can contain a declarations section followed by procedures. There may be many procedures in a module, but preferably the procedures should have some common theme. The declaration section can contain Option statements which set module-level options and must appear before any procedure. User defined type definitions Declarations any variable or constant declarations that are not contained within a procedure must be placed before any procedures in the module. Except for the three classes above, ALL code in VB must be contained within procedures. Procedures that access common data or provide a coherent set of actions can be grouped into the same module. Modules can be grouped into a single workbook, (or over several linked workbooks but that s too technical for this course). Creating procedures When you create a procedure you must decide how widely accessible you want it to be, what to name it, what task it will perform, what types of data it will accept and return. Specifying scope The term scope means the parts of the programme from which a variable, constant or procedure is accessible or visible. VB procedures can have either private or public scope. A procedure with private scope is visible only to other procedures in the same module; one with public scope is visible to all procedures in all modules in a workbook. Unless specified otherwise, procedures have public scope. To make a procedure private we use the Private keyword, Private Sub Savings() MsgBox A private procedure A private procedure cannot run as a stand-alone procedure; it can only be called from another procedure. 1

Naming procedures A procedure name must begin with a letter, not contain periods, mathematical or comparison operators, not exceed 255 characters, be unique within its scope not be the name of an existing VB method, function or property. Types of procedure There are two types: Sub procedures and Function procedures. A Sub procedure is enclosed between Sub and statements and performs a task but does not return a value. It may modify an Excel spreadsheet. A Function procedure is enclosed between Function and. It also performs some task but must also return a value. A function procedure is analogous to a mathematical function. It may not modify a spreadsheet, for example by deleting rows. For a function to return a value it must include a function assignment statement that gives a value to the name of the function. For example Function ConeSurface(radius, height) calculates the surface area of a right-cone given its radius and height Const Pi = 3.14159 conebase = Pi * radius ^ 2 coneside = Pi * radius * _ Sqr(radius ^ 2 + height ^ 2) ConeSurface = coneside + conebase The information for the function to perform its task (radius and height) is passed as arguments. This function may be used in an expression such as surfacecone = ConeSurface(3,10) in another procedure and also as a function in a workbook in which it is defined. In a cell you may type the formula =ConeSurface(3,10), or, for example, in cell C1 put =ConeSurface(A1,B1)if the radius and height data are stored in cells A1 and B1 respectively. [The function can be used in a workbook in which it is not defined provided you precede the function with the name of the workbook in which it is defined (Conebook.xls) and which must also be open, i.e. =CONEBOOK.XLS!ConeSurface(3,10).] Calling procedures There are two ways to call a Sub procedure 1. via a Call syntax with the arguments within brackets, e.g. Call MyProc(arg1, arg2) 2. without call and without brackets, e.g. MyProc arg1, arg2 Functions are called in the same way as built -in functions, =sin(x), e.g. 2

X = ConeSurface(radius, height) Arguments When you use an argument you can specify the data type, whether the procedure can change the argument s value whether an argument is required or is optional The arguments are included in brackets after the procedure name in its definition, e.g. Sub UpdateRecords(ownerID, ownername) is called in the following extract Dim newid As Integer, newname As String newid = 1467 newname = Joe Green UpdateRecords newid, newname Note that the name of the variable passed from the calling procedure does NOT have to be the same as the name of the argument declared in the definition of the called procedure. If an array is passed as an argument, you include empty brackets after the array name. Since the dimensions of the array are not defined, the procedure can accept arrays of any size, e.g. Sub CustomerList(customerArray()). Arguments have the same scope as variables declared within the procedure. They are not accessible outside the procedure in whose argument list they are declared. By default, procedure arguments have the Variant data type (see later notes). You can explicitly declare other data types using the As keyword in the declaration, e.g. Function ReverseText(text As String, n As Integer) reverses the first n characters in text Dim temp As String, i As Integer check on n compared to number of characters in text If n > Len(text) Then n = Len(text) fill temp with characters reversed For i = n To 1 Step -1 temp = temp & Mid(text, i, 1 ) Next i ReverseText = temp & Right(text, Len(text) n) Passing arguments by Reference or by Value This discussion is quite technical and initially can be ignored. It is, however, one cause of errors in programmes and so could be looked at on a second pass through the material. If you pass an argument by reference when calling a procedure it has access to the actual variable in memory and so can change its value. This is the default mode in VB. The statement Sub Pass(ByRef passedvariable As Integer) has the same effect as the statement Sub Pass(passedVariable As Integer). 3

If you pass an argument by value when calling a procedure the called procedure only gets a COPY of the variable. Hence if the called procedure changes its value it only affects the copy and the original va riable is unchanged. Passing variables by value therefore protects the original data from being changed accidentally by the called procedure. Compare the two cases below. TestArgs calls the procedure AddTen with the arguments passed by reference or by value. The numerical outcomes are very different! Sub TestArgs() Dim vartopass As Integer vartopass = 4 AddTen vartopass MsgBox vartopass this displays 14 Sub Addten(ByRef passedvar As Integer) passedvar = passedvar + 10 Msgbox passedvar this also displays 14 When TestArgs is run the message box display the number 14. If on the other hand we had passed the argument by value and defined Sub AddTen(ByVal passedvar As Integer) passedvar = passedvar + 10 Msgbox passedvar this displays 14 we would find that the message box in TestArgs would display the number 4, not 14 because AddTen only received a copy of the argument passedvar and could not change the original. Note that passedvar is NOT available in TestArgs in either case. If a data type is specified for an argument passed by reference you must pass a value of that type. On the other hand if the argument is passed by value, you need not pass a value of the same data type as the argument. There is one error that is produced by sloppy typing. If the argument is to be passed by reference then the statements Call AddTen(passedVar) or AddTen passedvar will do so. However if the Call is inadvertently omitted from the first syntax so that you write AddTen(passedVar), then the argument is passed by value and the outcome is different as in the previous example. Beware! Optional arguments The Optional keyword can be used in the argument list to specify that some of the arguments to the procedure are optional. If used, all subsequent arguments in the list must be optional. (Optional arguments must be of the Variant type). For example Sub List(startRow As Integer, startcol As Integer, _ 4

Optional newtext, Optional oldtext) When this procedure is called we could use List 2, 4, False, True List 2, 4,, True Named arguments Many built-in functions and methods take several optional arguments. Commas would be needed for all the missing ones and typing errors are liable to occur. You can use named arguments instead. VB associates argument names with the procedure. So the List procedure could be called in the following way. List newtext:= False, startrow:= 2, startcol:= 4 Note the syntax := after each argument name, and also that the named arguments can be given in any order. Indefinite number of arguments Usually the number of arguments in the calling of a procedure must be the same as in the procedures definition. The use of the ParamArray keyword allows you to specify that the procedure will accept an arbitrary number of arguments. (The argument used with ParamArray must be an array of Variant variables). The ParamArray keyword can only be used with the last argument in the list. The following procedure will work with any number of arguments. Function AddIntegers(ParamArray intnumbers()) Dim j As Integer, y As Variant For Each y In intnumbers x = x + y Next y AddIntegers = x This procedure could be called by AddIntegers(1, 3, 7) where three arguments are supplied or by AddIntegers(1, 3, 7, 9, 11, 13, 15)if seven are given. Exiting procedures Procedures usually run from the first statement to the last. Occasionally you may need to exit earlier, e.g. an error has occured in the procedure that makes it necessary to quit. Use Exit Sub and Exit Function to exit the procedure in a controlled manner. Exit statements are convenient but should not be overused as it makes the code difficult to read and debug. 5