VBA Handout. References, tutorials, books. Code basics. Conditional statements. Dim myvar As <Type >

Similar documents
DATABASE AUTOMATION USING VBA (ADVANCED MICROSOFT ACCESS, X405.6)

Appendix A1 Visual Basics for Applications (VBA)

Review for Programming Exam and Final May 4-9, Ribbon with icons for commands Quick access toolbar (more at lecture end)

DroidBasic Syntax Contents

Function Exit Function End Function bold End Function Exit Function

Language Fundamentals

Visual Basic for Applications

IDENTIFYING UNIQUE VALUES IN AN ARRAY OR RANGE (VBA)

Sub Programs. To Solve a Problem, First Make It Simpler

Introduction to Arrays. Midterm Comments. Midterm Results. Midterm Comments II. Function Basics (Problem 2) Introduction to Arrays April 11, 2017

Syntax. Table of Contents

Visual basic tutorial problems, developed by Dr. Clement,

LSP 121. LSP 121 Math and Tech Literacy II. Topics. More VBA. More VBA. Variables

Outline. Midterm Review. Using Excel. Midterm Review: Excel Basics. Using VBA. Sample Exam Question. Midterm Review April 4, 2014

Objects and Basic Programming Concepts (See Chapters 5 (skip ED 3), 6 of Albright) (See Chapters 5 (skip ED 4), 6 of Albright)

The For Next and For Each Loops Explained for VBA & Excel

ENGG1811 Computing for Engineers Week 7 Iteration; Sequential Algorithms; Strings and Built-in Functions

Civil Engineering Computation

EXCEL WORKSHOP III INTRODUCTION TO MACROS AND VBA PROGRAMMING

Function: function procedures and sub procedures share the same characteristics, with

LmÉPï C Á npï À ƵÀ ïì itech Analytic Solutions

Functions. Systems Programming Concepts

Visual Basic for Applications

Basic Programming Algorithms. 1-D Arrays

6/14/2010. VBA program units: Subroutines and Functions. Functions: Examples: Examples:

Question Points Score Total 100

HOW TO ACE THE 21 MOST COMMON QUESTIONS IN VBA 1

Level 3 Computing Year 2 Lecturer: Phil Smith

Good Variable Names: dimensionone, dimension1 Bad Variable Names: dimension One, 1dimension

CSE 123 Introduction to Computing

LSP 121. LSP 121 Math and Tech Literacy II. Topics. Loops. Loops. Loops

Review Functions Subroutines Flow Control Summary

References. Iteration For. Iteration (Repetition) Iteration While. For loop examples

Pace University. Fundamental Concepts of CS121 1

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

VBA Collections A Group of Similar Objects that Share Common Properties, Methods and

Module 3 - Applied UDFs - 1

A guide to writing Excel formulas and VBA macros. Mark McIlroy

Microsoft Office Excel Use Excel s functions. Tutorial 2 Working With Formulas and Functions

Excel Programming with VBA (Macro Programming) 24 hours Getting Started

Excel s VBA for Complete Beginners

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

1) Identify the recording mode, by which you can record the non-standard object in QTP

Introduction to VBA for Excel-Tutorial 7. The syntax to declare an array starts by using the Dim statement, such that:

KEYWORDS DDE GETOBJECT PATHNAME CLASS VB EDITOR WITHEVENTS HMI 1.0 TYPE LIBRARY HMI.TAG

Basic types and definitions. Chapter 3 of Thompson

Ms Excel Vba Continue Loop Through Range Of

References. Parameters revisited. Reference Parameters. Example: Swapping values. Named Arguments

DOWNLOAD PDF MICROSOFT EXCEL ALL FORMULAS LIST WITH EXAMPLES

Computational Methods of Scientific Programming. Lecturers Thomas A Herring Chris Hill

VBA Excel 2013/2016. VBA Visual Basic for Applications. Learner Guide

Download the files from you will use these files to finish the following exercises.

Excel Macro Record and VBA Editor. Presented by Wayne Wilmeth

IFA/QFN VBA Tutorial Notes prepared by Keith Wong

Fundamentals. Fundamentals. Fundamentals. We build up instructions from three types of materials

Chapter 4 The If Then Statement

MS Excel VBA Class Goals

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Using Application and WorksheetFunction objects

Scheme as implemented by Racket

A step by step guide to using the NAG Fortran Library with Microsoft Excel 2003


Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

References. Iteration For. Iteration (Repetition) Iteration While. For loop examples

VARIABLES. 1. STRINGS Data with letters and/or characters 2. INTEGERS Numbers without decimals 3. FLOATING POINT NUMBERS Numbers with decimals

What is a Function? What are functions good for?

Part 1 (80 points) Multiple Choice Questions (20 questions * 4 points per question = 80 points)

Sketchpad Graphics Language Reference Manual. Zhongyu Wang, zw2259 Yichen Liu, yl2904 Yan Peng, yp2321

Learning Excel VBA. About Variables. ComboProjects. Prepared By Daniel Lamarche

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Welcome To VTL Course

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

CpSc 111 Lab 5 Conditional Statements, Loops, the Math Library, and Redirecting Input

GNU ccscript Scripting Guide IV

I. True/False: (2 points each)

variables programming statements

General Syntax. Operators. Variables. Arithmetic. Comparison. Assignment. Boolean. Types. Syntax int i; float j = 1.35; int k = (int) j;

Revision for Final Examination (Second Semester) Grade 9

Flow Control: Branches and loops

CSI33 Data Structures

<excelunusual.com> Easy Zoom -Chart axis Scaling Using VBA - by George Lungu. < 1. Introduction: Chart naming: by George Lungu

Advanced Financial Modeling Macros. EduPristine

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

1007 Imperative Programming Part II

Built-in Types of Data

String Computation Program

MATLAB: The Basics. Dmitry Adamskiy 9 November 2011

Public Function randomdouble(lowerbound As Double, upperbound As Double) As Double On Error Resume Next

LECTURE 18. Control Flow

Excel Functions & Tables

Microsoft Excel. Good day All,

Excel Tool: Calculations with Data Sets

Haskell An Introduction

Variables are used to store data (numbers, letters, etc) in MATLAB. There are a few rules that must be followed when creating variables in MATLAB:

Miscellaneous Topics In Macro Programming

Learning Excel VBA. Using Loops in Your Code. ComboProjects. Prepared By Daniel Lamarche

CSE 123 Introduction to Computing

MATLAB provides several built-in statements that allow for conditional behavior if/elseif/else switch menu

Case Study Understanding code


Transcription:

VBA Handout References, tutorials, books Excel and VBA tutorials Excel VBA Made Easy (Book) Excel 2013 Power Programming with VBA (online library reference) VBA for Modelers (Book on Amazon) Code basics Comments start with a single quote: All variables require a type declaration Long for integers Double for floating point numbers String for strings Boolean for true or false variables Variant for a flexible type (anything but string) Declare variables as: Dim myvar As <Type > Variables can be declared inside or outside of functions or subroutines. Variables declared outside have a global scope. Indentation doesn t matter. Conditional statements If statements If condition Then ElseIf condition Then Else End If 1

Conditionals Equals, = Greater than, > Less than, < Greater than or equal to, >= Less than or equal to, <= Or And Not True False Ranges and Arrays Range variables come from cells in the worksheet. Declare a range variable Dim myrange As Range Set myrange =Range("A1:A20") Get or set the values contained in the range. Range("<Val >").Value Get a specific cell in a range at Row, Col. Range("<Val >"). Cells(Row, Col) Get or set the value in a given cell in a range. Range("<Val >"). Cells(Row, Col). Value Set the formula of a cell. Range("<Val >"). Cells(Row, Col). Formula Array variables Declare 1D Array: Dim myarray (100) As Double Declare 2D Array: Dim myarray(5, 8) As Double Access elements with (...): 2

' 1D a r r a y Dim myarray(5) As Double myarray(3) = 2 ' 2D a r r a y Dim myarray(5,5) As Double myarray(2,3) = 2 Initialize array directly from Range Variable Dim myarray as Variant myarray = myrange.value ' A l w a y s a 2D a r r a y Get array size from upper and lower bound Ubound( myarray) Lbound( myarray)+1 Loops For loop Do While loop Dim i As Long Dim istart As Long Dim iend As Long For i = istart To iend If i= istart +2 Then Exit For ' b r e a k t h e l o o p e a r l y End If Next i i = 0 Do While i < 100 i = i+1 Loop Do Until loop i = 0 Do Until i = 100 i = i+1 Loop 3

Subroutines and Functions Functions and subroutines are similar except functions can return a value and subroutines cannot. Arguments can be passed by value or by reference. Pass by value means a copy of a passed variable is made, so changes to it don t affect the orignal variable. Pass by reference means that if you pass a variable and change that argument inside the routine or function, then it changes the corresponding variable that was passed. This is useful for getting data out of a subroutine In VBA, pass by reference is the default Keywords: ByVal and ByRef. Also Optional for optional arguments Functions A function is called using its name, e.g. sum(5, 4) There is no explicit return statement in VBA. Instead we assign to the value to be returned to name of the function. The function will exit and return at the end, but you can exit early with Exit Function Subroutines Function sum(x As Double, y As Double) sum = x + y End Function A subroutine is called with Call mysubname(parameters). If there are no parameters, just use Call mysubname. Sub add_2_vals(x As Double, y As Double, _ sum As Double) ' x and y p a s s e d by r e f e r e n c e. I f c h a n g e d i n ' h e r e t h e v a r i a b l e s p a s s e d i n w i l l c h a n g e ' ( s a m e f o r sum, b u t t h a t i s by d e s i g n ). ' sum = x + y End Sub Sub add_2_vals(byval x As Double, ByVal y As Double, _ sum As Double) ' x, y p a s s e d by v a l u e. I f c h a n g e d h e r e, t h e ' v a r i a b l e s p a s s e d i n won ' t b e c h a n g e d. sum = x+y End Sub 4

Debugging The "Immediate Window" (View >Immediate Window) is useful for Debugging VBA code. Using the Debug.Print Command one can examine the value of variables or run functions. One can also run subroutines (via the Call command) in this window. In the Immediate Window, "?" is equivalent to Debug.Print Debug.Print myfunction (3)? myfunction (3) Call mysub(4) Useful Builtin VBA functions A pop-up message box: msgbox("a window will open with this message") msgbox("the value of myvar is " & mytemp & " (K)") Input box to get user input: myvariable = InputBox("Some message") Accessing individual cells ' G e t d a t a f r o m e x c e l c e l l B23 and s t o r e i t i n myvar myvar = Range("B23"). Value ' Put d a t a f r o m myvar i n t o c e l l B23 Range("B23"). Value = myvar Test if cell is empty, return true or false: IsEmpty(Range("B23")) Clear range of cells: Range("B5:B25"). Clear Grab the value in the cell that is up 3 and right 4 from the currently active cell. ActiveCell. Offset( 3, 4). Value Math functions: Abs, Int, Sqrt Exp, Log (natural log), Cos, Sin, Tan To get access to Excel worksheet functions: WorkSheetFunction. funcname(x,y, etc.)} 5