0% found this document useful (0 votes)
53 views

Excel VBA Lecture 0

VBA is a programming language that allows users to automate tasks in Excel and other Microsoft Office applications. It works by manipulating objects in Excel like cells, charts, and dialog boxes. Learning VBA enables users to do more than just normal spreadsheet functions. The language uses object-oriented programming principles where the object is written before the property or method. Code in VBA must be written on a single line with line breaks added using an underscore. Variables need to be declared using keywords like Dim and data types specified. Operators allow manipulation and comparisons of variable values.

Uploaded by

Kanahaiya
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

Excel VBA Lecture 0

VBA is a programming language that allows users to automate tasks in Excel and other Microsoft Office applications. It works by manipulating objects in Excel like cells, charts, and dialog boxes. Learning VBA enables users to do more than just normal spreadsheet functions. The language uses object-oriented programming principles where the object is written before the property or method. Code in VBA must be written on a single line with line breaks added using an underscore. Variables need to be declared using keywords like Dim and data types specified. Operators allow manipulation and comparisons of variable values.

Uploaded by

Kanahaiya
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Excel VBA

Introduction
Introducing Visual Basic for Applications
• Visual Basic for Applications or VBA is a development environment
built into the Microsoft Office Suite of products
• It's a programming language that enables you to control just about
everything in Excel/Office 365/2019 integrated applications.
• VBA is an Object Oriented Programming (OOP) language.
• It works by manipulating objects. In Excel worksheets, charts and
dialog boxes are also objects.
• Macros that can be run from a button on a spreadsheet, the Excel
Ribbon, etc.
• Learning Excel VBA will enable you to do a lot more with the software
than you can via the normal spreadsheet view.
Introducing Visual Basic for Applications
In VBA the object is written first

I’m fixing the Yellow House = .House.Yellow.Fix


House Yellow Fix
English .noun .adjective .verb
VBA .object .property .method

When working in VBA tell Excel exactly what to do. Don’t assume
anything
Introducing Visual Basic for Applications
• Write your code in lower case letters. If the spelling is RIGHT, the
Visual Basic Editor will capitalize the necessary letters. If it doesn't....
check your spelling
• All VBA sentences must be on a single line. When you need to write
long sentences of code and you want to force a line break to make it
easier to read you must add a space and an underscore at the end of
each line and then press Return.
Here is an example of a single sentence broken into 3 lines:
Range("C1:C9").Sort Key1:=Range("C2"), Order1:=xlAscending, _
MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortTextAsNumbers, Header:=xlYes
Introducing Visual Basic for Applications
Flickering Screen
Running a macro or VBA code may cause the screen to flicker as the
monitor is the slowest part of the program and cannot keep up with the
very fast changes taking place. To switch off the screen until the program
is run enter the following code line:
Application.ScreenUpdating = False
Screen comes on automatically on completion of the program

CutCopyMode
After each Paste operation, you should turn off copying:
ActiveSheet.Paste
Application.CutCopyMode = False
Introducing Visual Basic for Applications
DisplayAlerts

If you don't want Excel to ask you things like "Do you want to delete this
file..." you can use the following line of code at the beginning of the
relevant VBA procedure.

Application.DisplayAlerts = False

Then at the end make sure you use the following code to reactivate
Display Alerts.

Application.DisplayAlerts = True
Introducing Visual Basic for Applications
Compare Text

If you try to compare two strings in VBA, the system compares the Binary
information of the strings so that “My Name” Is Not Equal To “my name”.

To make the computer compare the words in the string, rather than the Binary
you need to enter the code: Option Compare Text In the Declarations area of the
module.

Quit

The following line of code closes Excel altogether.


Application.Quit
Introducing Visual Basic for Applications
Editing Macros in Visual Basic Editor

When you record a macro, the recorded instructions are inserted into a
Procedure whose beginning and end are denoted with the key words
Sub and End Sub. This is stored within a Module. A module can contain
many procedures.
Code generated when a macro is recorded can be modified to provide a
more customized function. To do this:
• Developer Ribbon > Code Section > Macros
• Select the desired macro from the Macro Name list
• Click Edit
The Visual Basic Editor appears.
Introducing Visual Basic for Applications

Project
Explorer
Code
Window

Properties
Window
Introducing Visual Basic for Applications
Absolute or Relative
During macro recording cell references can be made either relative to
the start position or with an absolute address.
By default, recorded macros use absolute cell referencing.
Understanding the difference:
When you use absolute references, selecting or moving from one cell to
another generates code that refers to that specific cell range.

In the case of relative references the code generated is a reference to a


cell in relation to the active cell (i.e. the cell initially selected)
Introducing Visual Basic for Applications
Protect/Lock Excel VBA Code
When we write VBA code it is often desirable to have the VBA Macro
code not visible to end-users. This is to protect your intellectual
property and/or stop users messing about with your code.
To protect your code, from within the Visual Basic Editor
Introducing Visual Basic for Applications
Shortcuts for VBA

Alt+F11 to Open the VB Editor


Ctrl+Space to Auto Complete
Ctrl + J to filter intellisense
F8 – Step through code
Ctrl+G – Immediate window
F5 to run the macro/user form
Introducing Visual Basic for Applications
Variable Declaration

Variables are declared using the DIM keyword


• The variable name can have no more than 255 characters.
• The variable name can contain letters and numbers but CANNOT start with a
number; it must start with a letter.
• Spaces are not allowed in the name, but it is common to use an “_” (underscore)
character to simulate a space.
• Certain special characters are not allowed, such as period, !, @, &, $, and #.
• You cannot use a name that already refers to a function, statement, method, or
intrinsic constant.
• You cannot declare two variables with the same name in the same scope level.
Option Explicit requires us to declare all variables.  When we see lines of code with
Dim statements at the top of a macro, this is declaring a variable.
Introducing Visual Basic for Applications
Data Types
Introducing Visual Basic for Applications
Dim & Set

Dim declares the variable.

Dim r As Range

reDim

reDim is used to change the size of one or more dimensions of an array that has already been declared

Dim MyArray() As String


ReDim MyArray(1)

Set sets the variable to an object reference.

Set r = Range("A1")
Introducing Visual Basic for Applications
Arithmetic Operators
Operator Description Example
+ Adds the two operands A + B will give 15

Subtracts the second operand from


- A - B will give -5
the first

* Multiplies both the operands A * B will give 50

Divides the numerator by the


/ denominator B / A will give 2

% Modulus operator and the remainder B % A will give 0


after an integer division

^ Exponentiation operator B ^ A will give 100000


Introducing Visual Basic for Applications
Comparison Operators
Operator Description Example

Checks if the value of the two operands are equal or not. If


= (A = B) is False.
yes, then the condition is true.

Checks if the value of the two operands are equal or not. If


<> (A <> B) is True.
the values are not equal, then the condition is true.

Checks if the value of the left operand is greater than the


> (A > B) is False.
value of the right operand. If yes, then the condition is true.

Checks if the value of the left operand is less than the value of
< (A < B) is True.
the right operand. If yes, then the condition is true.

Checks if the value of the left operand is greater than or equal


>= to the value of the right operand. If yes, then the condition is (A >= B) is False.
true.

Checks if the value of the left operand is less than or equal to


<= the value of the right operand. If yes, then the condition is (A <= B) is True.
true.
Introducing Visual Basic for Applications
Logical Operators

Operator Description Example


Called Logical AND operator. If both
AND the conditions are True, then the a<>0 AND b<>0 is False.
Expression is true.
Called Logical OR Operator. If any of
OR the two conditions are True, then a<>0 OR b<>0 is true.
the condition is true.
Called Logical NOT Operator. Used
to reverse the logical state of its
NOT operand. If a condition is true, then NOT(a<>0 OR b<>0) is false.
Logical NOT operator will make
false.
Introducing Visual Basic for Applications
Constants
Constant is a named memory location used to hold a value that
CANNOT be changed during the script execution. If a user tries to
change a Constant value, the script execution ends up with an error.
Constants are declared the same way the variables are declared.
Following are the rules for naming a constant.
• You must use a letter as the first character.
• You can't use a space, period (.), exclamation mark (!), or the
characters @, &, $, # in the name.
• Name can't exceed 255 characters in length.
• You cannot use Visual Basic reserved keywords as variable name.
Introducing Visual Basic for Applications
Example
Sub Constant_demo
Const MyInteger As Integer = 42
Const myDate As Date = #2/2/2020#
Const myDay As String = "Sunday"

MsgBox "Integer is " & MyInteger & Chr(10) & "myDate is "
& myDate & Chr(10) & "myDay is " & myDay
End Sub

You might also like