Vba Variables Constant and Data types in Excel

Similar documents
Excel VBA Variables, Data Types & Constant

Excel VBA Programming

Language Fundamentals

d2vbaref.doc Page 1 of 22 05/11/02 14:21

Unit 4. Lesson 4.1. Managing Data. Data types. Introduction. Data type. Visual Basic 2008 Data types

Microsoft Visual Basic 2015: Reloaded

Microsoft Visual Basic 2005: Reloaded

Programming Language 2 (PL2)

3. Java - Language Constructs I

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

Visual Basic for Applications

I

SKILL AREA 306: DEVELOP AND IMPLEMENT COMPUTER PROGRAMS

BASIC ELEMENTS OF A COMPUTER PROGRAM

Function Exit Function End Function bold End Function Exit Function

Introduction to Data Entry and Data Types

VB FUNCTIONS AND OPERATORS

Unit 6 - Software Design and Development LESSON 4 DATA TYPES

DEPARTMENT OF MATHS, MJ COLLEGE

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

Computers and Programming Section 450. Lab #1 C# Basic. Student ID Name Signature

Java Notes. 10th ICSE. Saravanan Ganesh

Visual C# Instructor s Manual Table of Contents

Object Oriented Programming with Visual Basic.Net

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Our Strategy for Learning Fortran 90

Chapter 2: Using Data

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

6.096 Introduction to C++ January (IAP) 2009

Creating a C++ Program

Programming in C++ 5. Integral data types

Java enum, casts, and others (Select portions of Chapters 4 & 5)

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Annotation Annotation or block comments Provide high-level description and documentation of section of code More detail than simple comments

CS313D: ADVANCED PROGRAMMING LANGUAGE

Lecture 3 Tao Wang 1

Chapter-8 DATA TYPES. Introduction. Variable:

EXCEL WORKSHOP III INTRODUCTION TO MACROS AND VBA PROGRAMMING

Computers Programming Course 5. Iulian Năstac

Outline. Data and Operations. Data Types. Integral Types

Programming in C++ 6. Floating point data types

The CPU and Memory. How does a computer work? How does a computer interact with data? How are instructions performed? Recall schematic diagram:

Lesson 02 Working with Data Types. MIT 31043: VISUAL PROGRAMMING By: S. Sabraz Nawaz Senior Lecturer in MIT

Computer Components. Software{ User Programs. Operating System. Hardware

3. Java - Language Constructs I

Appendix A1 Visual Basics for Applications (VBA)

MATVEC: MATRIX-VECTOR COMPUTATION LANGUAGE REFERENCE MANUAL. John C. Murphy jcm2105 Programming Languages and Translators Professor Stephen Edwards

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

UNIT- 3 Introduction to C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

CSE 123 Introduction to Computing


ENGINEERING 1020 Introduction to Computer Programming M A Y 2 6, R E Z A S H A H I D I

C++ Programming: From Problem Analysis to Program Design, Third Edition

Civil Engineering Computation

CS110: PROGRAMMING LANGUAGE I

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

Programming and Data Structures

Lesson 02 Working with Data Types MIT 31043, Visual Programming By: S. Sabraz Nawaz

On a 64-bit CPU. Size/Range vary by CPU model and Word size.

Visual basic tutorial problems, developed by Dr. Clement,

Primitive Data, Variables, and Expressions; Simple Conditional Execution

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

Variables and numeric types

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

[0569] p 0318 garbage

Introduction to C# Applications

CMSC 104 -Lecture 6 John Y. Park, adapted by C Grasso

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

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

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Variables in VB. Keeping Track

Control Properties. Example: Program to change background color

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

COMP-202: Foundations of Programming. Lecture 5: More About Methods and Data Types Jackie Cheung, Winter 2016

Chapter 2: Using Data

OUTLINE. Number system. Creating MATLAB variables Overwriting variable Error messages Making corrections Entering multiple statements per line

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

JME Language Reference Manual

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

Computer Programming CS F111

printf( Please enter another number: ); scanf( %d, &num2);

Overview (4) CPE 101 mod/reusing slides from a UW course. Assignment Statement: Review. Why Study Expressions? D-1

Overview About KBasic

Zheng-Liang Lu Java Programming 45 / 79

PART I. Part II Answer to all the questions 1. What is meant by a token? Name the token available in C++.

Introduction to Computer Use II

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

CHAPTER 3: CORE PROGRAMMING ELEMENTS

SPARK-PL: Introduction

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

MATLAB. Devon Cormack and James Staley

C Language Programming

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Basics of Programming

Transcription:

Vba Variables Constant and Data types in Excel VARIABLES In Excel VBA, variables are areas allocated by the computer memory to hold data. Data stored inside the computer memory has 4 properties: names, data type, value and address. Each variable must be given a name. To name a variable in Excel VBA, you have to follow a set of rules, as follows: Variable Names The following are the rules when naming the variables in VBA It must be less than 255 characters No spacing is allowed It must not begin with a number Period is not permitted Space is not allowed It should not be a keyword. Examples of valid and invalid variable names are displayed in below table DATA TYPES In VBA, we need to declare the variables before using them by assigning names and data types. There are many VBA data types, which can be grossly divided into two

types, namely the numeric data types and the non-numeric data types. i) Numeric Data Types Numeric data types are types of data that consist of numbers, which can be computed mathematically with various standard arithmetic operators such as Addition, Subtraction, Multiplication, Division and more. In VBA, the numeric data are divided into 7 types, which are summarized shown in below table. Data Type Size in Memory Description Range of Values Byte 1 byte Represents an unsigned (nonnegative) number - often used for binary data 0 to 255 Integer 2 bytes Integer (no decimals) -32,768 to +32,767 Long 4 bytes Long Integer (no decimals) Single 4 bytes Single Precision Floating Point Number Double 8 bytes Double Precision Floating Point Number Currency 8 bytes A Floating Point Number with a fixed number of decimal places -2,147,483,648 to +2,147,483,647-3.4e38 to +3.4e38-1.8e308 to +1.8e308-922,337,203,685,477.5808 t o +922,337,203,685,477.5807 From the above table, it is clear that you can save on memory by using specific data types (e.g. Integers rather than Longs, or Singles rather than Doubles). However, if you are planning to use the 'smaller' data types, you must be sure that your code will not encounter larger values than can be handled by the chosen data type. ii) Non-numeric Data Types Nonnumeric data types are summarized in below table

Data Type Size in Memory Description Range of Values Date 8 bytes Date & Time - The Date type is represented internally by a floating point number. The integer part of the number represents the date, and the decimal portion represents the time. Boolean 2 bytes A simple True or False value Object 4 bytes A reference to an object String varies Holds a series of characters. The String type can be defined to have a fixed or a variable length, although it is most commonly defined to have a variable length Variant varies Can hold Dates, Floating Point Numbers or Strings of Characters, and should therefore be used when you are not sure what type of data to expect. 1st January 100 to 31st December 9999 True or False Any Object Reference Fixed - Up to 65,500 characters Variable - Up to approx. 2 billion characters Number - same as Double Type String - same as String Type Declaring Variables You can declare the variables implicitly or explicitly. For example, sum=text1.text

means that the variable sum is declared implicitly and ready to receive the input in textbox1. Other examples of implicit declaration are: volume=10 label= Dreams. If the data type is not specified, VBE will automatically declare the variable as a Variant (Variant means the variable can hold any numeric data type). On the other hand, for explicit declaration, variables are normally declared in the general section of the code window using the Dim statements. Here is the syntax: Dim Variable_Name As Data_Type Note that in the above line of code, Variable_Name should be replaced by your actual variable name and Data_Type should be replaced by one of the above listed data types. For example: Example: Dim Dreams As String Dim ename As String Dim fnumber As Integer Dim snumber As Integer Dim sumall As Integer Dim bdate As Date You may also combine them into one line, separating each variable with a comma, as follows: Dim Dreams As String, ename As String, fnumber As Integer. For string declaration, there are two possible formats, one for the variable length string and another for the fixed-length string. For the variable-length string, just use the same format as mentioned above. However, for the fixed-length string, you have to use the format as shown below: Dim VariableName as String * n Where n defines the number of characters the string can hold. For example, Dim yourname as String * 10

mean ename can hold no more than 10 Characters. In this example, we declared three types of variables, namely the string, date and currency. Private Sub CommandButton1_Click() Dim fname As String, bdate As Date, Salary As Currency fname = "ABC" bdate = "23 Nov 1981" Salary = 1000 Range("A1") = fname Range("A2") = bdate Range("A3") = Salary End Sub DECLARING CONSTANT Constant is similar to variable except that it has a fixed value that will never change. For example, you might use the constant "Pi" to store the value 3.14159265... The value of "Pi" will not change throughout the course of your program, but it is useful to store this value in a Constant for ease of use. Also, we might use a variable named "svat_rate", to store the VAT Rate to be paid on purchased goods. The value of svat_rate may vary, depending on the type of goods. Constants are declared in a similar way, except a constant should always be assigned a value when it is declared. Examples of the declaration of constants in VBA are: Const imaxcount=5000 Const imaxscore = 100 REASONS TO DECLARE VARIABLES Excel does not force you to declare variables. By default, all variables in Excel will have the Variant type, and can be assigned a number or text. Therefore, at any point during your program, you can use any variable name (even if it has not been declared), and Excel will assign the Variant type to it. However, it is not good programming practice not to declare variables for the following reasons:

Memory & Calculation Speed: If you do not declare a variable to have a data type, it will, by default, have the Variant type. This takes up more memory than many of the other data types. While a few extra bytes per variable might not seem to be a lot of memory, it is not uncommon for programmers to have thousands of variables in their programs (especially when you start to use arrays). Therefore, the additional memory used to store Variants instead of Integers or Singles, can add up significantly. Variant data types also take more time to process than some of the other data types, so if you have thousands of unnecessary Variant data types, this can slow down your calculations. Prevention of 'Typo' Bugs: If you always declare your variables, then you can use the VBA Option Explicit (see below) to force you to declare variables. This will prevent you from introducing bugs into your code by accidentally typing a variable name incorrectly. For example, you might be using a variable called "svat_rate" and, when assigning a value to this variable, you might accidentally type "VATRate = 0.175". From this point onwards, you are expecting your variable "svat_rate" to have the value 0.175, but of course it doesn't. However, if you had been using the VBA option Explicit to force you to declare all variables before using them, this error would be highlighted by the VBA compiler, as the variable "VATRate" would not have been declared. Highlighting Unexpected Data Values: If you declare a variable to have a specific data type, and you attempt to assign the wrong type of data to it, this will generate an error in your program which, if not handled within your code, can cause your programme to crash. While this may initially seem to be a good reason not to declare variables, it is actually useful to know as soon as possible if your variable receives an unexpected data type. Otherwise, if the program continues to run, you could end up with incorrect or unexpected results at a later time, when it is likely to be much more difficult to detect the causes of the errors. Also, it is possible that the macro may complete with incorrect results, and you may not notice the error at all - and continue to work with incorrect data!

It is therefore preferable to detect the unexpected data type at an early stage and add code to handle this appropriately. Due to the reasons listed above, it is recommended that you always declare all variables when programming in VBA, and use the Option Explicit (see below) to ensure that all variables in the code are declared. THE USE OF OPTION EXPLICIT The use of Option Explicit is to help us to track errors in the usage of variable names within a program code. For example, if we commit a typo, VBE will pop up an error message Variable not defined. Indeed, Option Explicit forces the programmer to declare all the variables using the Dim keyword. It is a good practice to use Option Explicit because it will prevent us from using incorrect variable names due to typing errors, especially when the program gets larger. With the usage of Option Explicit, it will save us time in debugging our programs. If you want to always include the option Explicit at the top of every new VBA module that you open up, this can be done automatically via the 'Require Variable Declaration' option of your VBA editor. To activate this: In the Visual Basic Editor, select Tools Options...; Ensure the Editor tab is selected; Check the box next to the option Require Variable Declaration and click OK. Once the 'Require Variable Declaration' option is selected, the Option Explicit will automatically be inserted at the top of all new modules in the VBA Editor. When Option Explicit is included in the program code, we have to declare all variables with the Dim keyword. Any variable not declared or wrongly typed will cause the program to popup the Variable not defined error message. We have to correct the error before the program can continue to run. This example uses the Option Explicit keyword and it demonstrates how a typo is being tracked.

Option Explicit Private Sub CommandButton1_Click() Dim myname As String, pass As String myname = "John" pass = 12345 Cells(1, 2) = mynam Cells(1, 3) = pass End Sub The typo is mynam and the error message variable not defined is displayed. ASSIGNMENT STATEMENT (ASSIGNING VALUES TO THE VARIABLES) After declaring various variables using the Dim statements, we can assign values to those variables. The general format of an assignment is Variable=Expression The variable can be a declared variable or a control property value. The expression could be a mathematical expression, a number, a string, a Boolean value (true or false) and more. Here are some examples: firstnumber=100 secondnumber=firstnumber-99 username="john Lyan" userpass.text = password Label1.Visible = True Command1.Visible = false ThirdNumber = Val(usernum1.Text) total = firstnumber + secondnumber+thirdnumber SOURCE: http://www.excelfunctions.net/vba-variables-and-constants.html