0% found this document useful (0 votes)
62 views48 pages

3 Vba Fundamentals m3 Lang1 Slides

The document provides an overview of the key concepts in the VBA language, including: 1) VBA projects contain modules, class modules, userforms, and other components for organizing code. 2) The main data types in VBA include variants, strings, integers, booleans, floating point numbers, dates, enums, and objects. 3) Operators allow performing actions like arithmetic, comparison, logical operations, and bitwise operations. 4) Essential functions exist for arrays, conversions, date/time, file system, information, interaction, math, strings, and worksheet functions.

Uploaded by

Rajesh Kanna N
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views48 pages

3 Vba Fundamentals m3 Lang1 Slides

The document provides an overview of the key concepts in the VBA language, including: 1) VBA projects contain modules, class modules, userforms, and other components for organizing code. 2) The main data types in VBA include variants, strings, integers, booleans, floating point numbers, dates, enums, and objects. 3) Operators allow performing actions like arithmetic, comparison, logical operations, and bitwise operations. 4) Essential functions exist for arrays, conversions, date/time, file system, information, interaction, math, strings, and worksheet functions.

Uploaded by

Rajesh Kanna N
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

The VBA Language

Part 1

Terry Bradbury
[email protected]
Overview

 The VBA Project and Components


 Data Types
 Objects
 Operators
 Essential Functions
The VBA Project

 Top-level container for all application components


 Can be accessed and modified through code
 Requires a reference to Microsoft Visual Basic for Applications Extensibility
 Requires the ‘Trust access to the VBA project object model’ option to be set
in the Trust Center
 Automating the project should never be used for applications
 Only developer tools and add-ins
VBA Components

 Directly below the project in the Project Explorer


 Four Types of Components
 Documents (application-specific)
 Modules (general-purpose code containers)
 Class Modules (for creating non-visual objects)
 UserForms (for creating custom dialogs)
 Interfaces
 Created as Class Modules
 Implemented in Class Modules or UserForms
Modules
Class Modules
UserForms
Interfaces
Project Organization
Data Types

 Variant type
 String type
 Integer types
 Boolean type
 Floating-point types
 Scaled types
 Date type
 Enumerations
 Object types
 User-Defined types
Variant Data Type

 The default data type


 Special ‘container’ that can hold any type of data
 Including arrays or objects
 Automatically takes on the correct data type on assignment
 Often used in ‘For Each’ or other types of loops
 Carries some overhead as the price for flexibility
 Don’t use unless necessary
 Default value is Empty
String Data Type

 For holding character (non-numeric) data


 Two forms of strings
 Variable length (~2B characters)
 Fixed length (1 to 64K characters)
 VBA code will not compile if you declare a string >64K
 Default value for variable length is an empty string (“”)
 Default value for fixed length is the size of the string filled with spaces
 All strings are stored internally as Unicode
 Automatically converted to ANSI as needed
Integer Data Types

 Byte (1 byte)
 0 to 255
 Integer (2 bytes)
 -32,768 to 32,767
 Long (4 bytes)
 -2,147,483,648 to 2,147,483,647
 LongLong (8 bytes – only on 64-bit systems)
 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
 LongPtr
 Same as Long (Dword) on 32-bit systems
 Same as LongLong (Qword) on 64-bit systems
 The default value for all Integer types is 0
Boolean Data Type

 Used for storing True or False values


 Default value is False
 Stored as 16-bit (2-byte) integers, but can only be True or False
 When numerics are converted to Boolean, 0 = False, anything else =
True (Not False)
 When Booleans are converted to numbers, False = 0, True = -1
Bits and Nibbles and Bytes (oh my!)

 The most basic unit of information in computing is the bit


 Can have 2 values – 0 (cleared) and 1 (set)
 You can ‘flip’ a bit to toggle between 0 and 1
 A group of 4 bits is a nibble
 A group of 8 bits is a byte (2 nibbles) sometimes called an octet
 Groups of bytes are often referred to as words
 Word (2 bytes – 16 bits)
 Dword (4 bytes – 32 bits)
 Qword (8 bytes – 64 bits)
 Use string data type to store and display bit representations
Positional Values

 Values are based on their position


 Bits are usually ordered from right to left
 Least Significant Bit is on the right
 Most Significant Bit is on the left
 Bit numbering systems
 LSB 0 means the LSB is numbered as bit 0 (right to left) 76543210
 MSB 0 means the MSB is numbered as bit 0 (left to right) 01234567
 Bit values can be determined by power of 2 for their position
 2^0 = 1
 2^1 = 2
 2^2 = 4
 2^3 = 8, etc…
Signed and Unsigned Values

 Unsigned max value equals the sum of all the bit values
 Signed max is half the sum of all bit values
 Set MSB to indicate a negative value
Writing Binary

Binary Decimal
0000 0000 = 0
0000 0001 = 1
0000 0010 = 2
0000 0011 = 3

0000 0010 0010 0101


And 0001 0110 Or 0001 0010 Not 0101
= 0000 0010 = 0011 0111 = 1010
(2) (55) (10)
Just Remember…

There are only 10 types of


people in the world:
Those who understand binary
and those who don't.
Floating-Point Data Types

 Single
 Negative values between -3.402823 x 1038 and -1.401298 x 10-45
 Positive values between 1.401298 x 10-45 and 3.402823 x 1038
 Double
 Negative values between
-1.79769313486232 x 10308 and -4.94065645841247 x 10-324.
 Positive values between
4.94065645841247 x 10-324 and 1.79769313486232 x 10308.
 Will have rounded values for some expressions such as 1/3
Scaled Data Types

 Currency (8 bytes)
 15 digits to the left of the decimal, 4 to the right
 In the range of -922,337,203,685,477.5808 to 922,337,203,685,477.5807
 Decimal (12 bytes)
 Can have up to 28 decimal places
 Is a subtype of variant
 Use CDec to convert to decimal
Date Data Type

 Contains both date and time


 Stored internally as an 8-byte floating-point value
 The integer portion stores the number of days since December 30, 1899
 The decimal portion stores the number of seconds since midnight
 The default value is 12/30/1899 00:00:00
 Date literals are assigned using # as a delimiter (#m/d/y h:m:s#)
 Integer values can be added or subtracted to modify the day
Enumerations

 System or User-defined collections of constants


 Internal data type is long
 Three categories:
 Sequential
 Assigned
 Composite (Bitwise)
Object Types

 There are 4 types of ‘objects’


 The ‘object’ data type
 Contains a reference to an object
 Used for ‘late binding’
 No IntelliSense available
 Errors cannot be discovered until runtime
 An instantiated class from the object model
 Use Class Modules for creating user-defined objects
 Can implement custom properties, events and methods
 Must be instantiated before use
 UserForms for custom dialogs
User-Defined Types

 A user-defined grouping of other types


 Sometimes called a Structure in other languages
 Often used in Windows API calls
 VBA version must be created to use this type of call
 Easier to use than a Class Module
 Everything is directly addressable (no properties)
 Simple declaration to use – no instantiation
 No data protection, validation or events
Objects

 ErrObject (Err)
 Collection
 Global
ErrObject

 Contains data about the last error


 Can be programmatically invoked using Err.Raise
 Can be cleared by using Err.Clear or any form of On Error Resume
Collections

 Can be thought of as an ‘object’ version of an array


 Uses properties and methods to add/remove/locate items
 Can store simple types or objects
 Many global objects are Collections
Global

 Provides the global UserForms collection


 Contains references to all loaded UserForms
 Also provides methods for loading and unloading UserForms
Operators
General-Purpose Operators

 Assignment ( = )
 x = y + z
 Set wks = ActiveSheet
 Concatenation ( & )
 FullName = FirstName & " " & LastName
 TheAnswer = "Answer to the Ultimate Question of Life, " _
& "the Universe, and Everything is " & 42 & "."
Arithmetic Operators

 The standard arithmetic operators ( + - * / )


 Division usually results in a Double (there are exceptions)
 Integer division ( \ Mod )
 There are no increment or decrement operators ( use + 1 or – 1)
 Exponent ( ^ ) answer = base ^ power
 Operator Precedence
 Exponentiation ( ^ )
 Negation ( - )
 Multiplication and division ( *, / )
 Integer Division ( \ )
 Modulus arithmetic (Mod)
 Addition and subtraction ( +, - )
 String concatenation
 Always use parentheses instead of depending on order of precedence
Comparison Operators

 Equality ( = )
 Inequality ( <> )
 Less than ( < )
 Greater than ( > )
 Less than or equal to ( <= )
 Greater than or equal to ( >= )
 Pattern matching ( Like )
 Object reference comparison ( Is )
 If (Obj1 Is Obj2) Then ' both reference same object
 If (Obj1 Is Nothing) Then ' does not refer to any object
Bitwise Operators

 And
 Returns bits set in both values
 Or
 Returns bits set in either value
 Xor (exclusive Or)
 Returns bits that are different in both values
 Not
 Flips all the bits in a value
Logical Operators

 And (Conjunction)
 If ((2 + 2 = 4) And (4 + 4 = 8)) Then ' True
 Or (Disjunction)
 Xor (Exclusion)
 Not (Negation)
 Eqv (Equivalence)
 Imp (Implication)
Essential Functions

 Array
 Conversion
 DateTime
 FileSystem
 Information
 Interaction
 Math
 String
 Worksheet Functions (Excel only)
Array Functions

 Array
 Join
 Split
 LBound
 UBound
 Erase
 Filter
Conversion Functions

 CBool, CByte, CCur, CDate, CDbl, CSng, CInt, CLng, CLngLng, CLngPtr,
CStr, CVar
 CDec
 Can only be used with a variant
 Hex, Hex$, Oct, Oct$
 Int, Fix
 Str, Str$
 Val
DateTime Functions

 Now
 Date, Date$, Time, Time$
 Year, Month, Weekday, Day, Hour, Minute, Second
 Timer
 DateAdd
 DateDiff
 DatePart
 DateSerial, TimeSerial
 DateValue, TimeValue
FileSystem Functions

 ChDir  Input
 ChDrive  Kill
 CurDir, CurDir$  Loc
 Dir  Lock, Unlock
 MkDir, RmDir  Open, Close, Reset
 Print
 EOF, LOF  Seek
 FileAttr  SetAttr
 FileCopy
 FileDateTime
 FileLen
 FreeFile
Financial Functions
 DDB (double-declining balance)
 FV (future value)
 IPmt (interest payment)
 IRR (internal rate of return)
 MIRR (modified internal rate of return)
 NPer (number of periods)
 NPV (net present value)
 Pmt (payment)
 PPmt (principal payment)
 PV (present value)
 Rate (rate)
 SLN (straight-line depreciation)
 SYD (sum-of-years' digits depreciation)
Mathematic Functions

 Abs (absolute)
 Atn (arctangent)
 Cos (cosine)
 Exp (exponent)
 Log (logarithm)
 Randomize
 Rnd (random)
 Round (rounded)
 Sgn (sign)
 Sin (sine)
 Sqr (square root)
 Tan (tangent)
String Functions

 Asc, AscB, AscW  LCase, LCase$, UCase, UCase$


 Chr, Chr$, ChrB, ChrB$,  LTrim, LTrim$, RTrim, RTrim$,
ChrW, ChrW$ Trim, Trim$
 Filter, Join, Split  MonthName, WeekdayName
 Format, Format$,  Replace
FormatCurrency ,  StrComp
FormatDateTime ,  StrConv
FormatNumber, FormatPercent
 StrReverse
 InStr, InStrB, InStrRev
 String, Space
 Left, Left$, LeftB, LeftB$,
Right, Right$, RightB, RightB$,
Mid, Mid$, MidB, MidB$
 Len
Information Functions

 IsArray
 IsDate
 IsEmpty
 IsError
 IsMissing
 IsNull
 IsNumeric
 IsObject
 QBColor
 RGB
 TypeName
 VarType
Interaction Functions

 AppActivate, Shell
 Beep
 CallByName
 Choose, IIf, Switch
 CreateObject, GetObject
 DoEvents
 Environ, Environ$
 GetSetting, GetAllSettings, DeleteSetting, SaveSetting
 InputBox
 MsgBox
 SendKeys
Worksheet Functions

 For Excel solutions, native worksheet functions can be used in VBA


 Use Application.WorksheetFunction.<FunctionName>
 Functions operate on a Range
 Provides many advanced functions not available in VBA
A Better Way…
Summary

 The VBA Project and Components


 Data Types
 Objects
 Operators
 Essential Functions

You might also like