Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
18 views102 pages

VBA Programming Fundamentals

Chapter 8 covers the fundamentals of VBA programming, including its purpose for automating tasks in Excel, the structure of VBA modules, and the types of procedures (Sub and Function). It explains the object-oriented nature of VBA, detailing objects, properties, methods, and collections, along with practical examples and coding practices. The chapter also includes exercises to reinforce learning and application of the concepts discussed.

Uploaded by

Trang Trịnh
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)
18 views102 pages

VBA Programming Fundamentals

Chapter 8 covers the fundamentals of VBA programming, including its purpose for automating tasks in Excel, the structure of VBA modules, and the types of procedures (Sub and Function). It explains the object-oriented nature of VBA, detailing objects, properties, methods, and collections, along with practical examples and coding practices. The chapter also includes exercises to reinforce learning and application of the concepts discussed.

Uploaded by

Trang Trịnh
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/ 102

Chapter 8.

VBA Programming
Fundamentals
Table of Content
1. Introduction
2. VBA Fundamentals
3. VBA Language Elements and Comments
4. Variables, Data Types, and Constants
5. Assignment Statements
6. Object Variables
7. Built-in Functions
8. Manipulating Objects – With-End With
9. Manipulating Collections – For-Next
10. Controlling Code Execution
2
List of Practice
1. Practice 8.1
2. Practice 8.2
3. Practice 8.3
4. Practice 8.4
5. Practice 8.5
6. Practice 8.6
7. Practice 8.7
8. Practice 8.8
9. Practice 8.9
10. Practice 8.10

3
1. Introduction - VBA

▪ Visual Basic for Applications (VBA) is a powerful programming


language built into Excel, which you can use to automate routine or
repetitive tasks, create custom worksheet formulas, or develop
Excel-based applications for other users.

▪ Therefore, VBA saves time, especially when working with repetitive


works.

▪ Example: Create 50 new worksheets, where each worksheet's name


corresponds to a customer's name. Or create a new function.

4
1. Introduction – Code, Module and Procedures

▪ You perform actions in VBA by executing VBA code. You write (or
record) VBA code which is stored in a VBA module.

▪ VBA modules are stored in an Excel workbook file. A VBA module


consists of procedures.

▪ A procedure is a block of code that performs some actions. VBA


supports two types of procedures: Sub procedures and Function
procedures.

▪ An Excel workbook is like a bookshelf holding many books, where


each book represents a VBA module.
5
1. Introduction - Sub and Function procedures

▪ A sub procedure perform actions but do not return a value. Here’s


an example of a simple Sub procedure called Test: This procedure
calculates a simple sum and then displays the result in a message
box.

Sub Test()
Sum = 1 + 1
MsgBox "The answer is " & Sum
End Sub

6
1. Introduction - Sub and Function procedures

▪ A function procedure returns a single value (or possibly an array). A


Function can be called from another VBA procedure or used in a
worksheet formula. Here’s an example of a Function named
AddTwo:
Function AddTwo(arg1, arg2)
Addtwo = arg1 + arg2
End Function

7
1. Introduction – VBE Components
▪ You view or edit a module by using Visual Basic Editor (VBE). To
see this hidden VBE environment, you need to activate it. The
quickest way to activate the VBE is to press Alt+F11 when Excel is
active. To return to Excel, press Alt+F11 again.
▪ You can also activate the VBE by using the Visual Basic command
on Excel’s Developer tab.
▪ Components of VBE:
▪ Menu bar: The VBE menu bar contains commands that you use
to do things with the various components in the VBE.
▪ Toolbar: The Standard toolbar is directly under the menu bar
by default. 8
1. Introduction – VBE Components
▪ Components of VBE:
▪ The project window displays a tree diagram that shows every
workbook currently open in Excel. If the Project window is not
visible, press Ctrl+R or use the View ➪ Project Explorer
command.
▪ A code window contains VBA code. To view an object’s Code
window, double-click the object in the Project window.
▪ The immediate window execute individual VBA statements. It
may or may not be visible. If it isn’t visible, press Ctrl+G or use
the View ➪ Immediate Window command.
9
1. Introduction – VBE Components
▪ Components of VBE:
▪ The locals window displays all of the declared variables in the
current procedure and their values. When the Locals window
is visible, it is automatically updated every time there is a
change of a variable. It is helpful to trace through each line of
code and steps into procedures. This allows you to view the
effect of each statement on variables.

10
1. Introduction – VBE
Components

11
1. Introduction – Immediate Window
▪ You can use the Immediate Window to test a line of code or to
display result of a line of code.
▪ To execute code in the Immediate window:
▪ Type a line of code in the Immediate window
▪ Press ENTER to execute the statement
▪ Enter the following line of code in the Immediate window display a
message.
Msgbox "Hello World!"

12
1. Introduction – Immediate Window
▪ If you want to run multiple lines of code, use colon : between them.
▪ Enter the following lines of code in the Immediate Window to
display 2 messages.
Msgbox "Hello World!": Msgbox "Welcome to the course"
▪ You can print the result of a line of code in the Immediate Window
by using Question mark ? or Print command.
▪ Enter the following line of code in the Immediate window returns
the result of the equation.
? 123*123
Print 123*123
13
1. Introduction – VBA Module
▪ A single VBA module can store any number of Sub procedures,
Function procedures.
▪ Follow these steps to add a new VBA module manually to a project:
▪ 1. Select the project’s name in the Project window.
▪ 2. Choose Insert ➪ Module.
▪ Or you can do the following:
▪ 1. Right-click the project’s name.
▪ 2. Choose Insert ➪ Module from the shortcut menu.

14
1. Introduction – VBA Module

15
1. Introduction – Getting VBA Code into a Module

▪ You can get VBA code into a VBA module in three ways.

▪ Use the Excel macro recorder to record your actions and


convert them to VBA code. However, not all tasks can be
translated to VBA by recording a macro.

▪ Enter the code directly.

▪ Copy the code from one module and paste it into another.

16
1. Introduction – Getting VBA Code into a Module

▪ Create your first VBA Code by type the following code into the
module.
Sub GuessName()
Dim Msg as String
Dim Ans As Long
Msg = "Is your name " & Application.UserName & "?"
Ans = MsgBox(Msg, vbYesNo)
If Ans = vbNo Then MsgBox "Oh, never mind."
If Ans = vbYes Then MsgBox "I knew it!"
End Sub

▪ Press F5 or play button to execute the procedure.


17
2. VBA Fundamentals – Objects

▪ VBA is an object-oriented programming language. The basic


concept of object-oriented programming is that a software
application (Excel in this case) consists of various individual object.

▪ Each object has its own set of attributes, which are called properties,
and its own set of actions, called methods.

▪ For example: workbook is an object with attributes (properties), such


as its name, the number of worksheets it contains, and the date it
was created. A workbook object also has actions (methods) such as
Open, Close, and Save.
18
2. VBA Fundamentals – Objects

▪ Object classes are arranged in a hierarchy.

19
2. VBA Fundamentals – Objects

▪ To view all the


objects available in
VBA, you can use
the Object Browser
by pressing F2 or
going to the menu
and select View ➪
Object Browser.

20
2. VBA Fundamentals – Objects

▪ To view all the objects available in VBA, you can also go to the
website: https://learn.microsoft.com/en-
us/office/vba/api/overview/excel/object-model

▪ To point to a specific object in VBA, you can traverse the object


model. For example, to get to cell A1 on Sheet 1, you can enter this
code:

Application.ThisWorkbook.Sheets("Sheet1").Range("A1").Select

21
2. VBA Fundamentals – Objects

▪ In most cases, the object model hierarchy is understood, so you don’t


have to type every level. Entering this code also gets you to cell A1
because Excel infers that you mean the active workbook and the
active sheet:
Range("A1").Select

▪ If you have your cursor already in cell A1, you can simply use the
ActiveCell object, negating the need to spell out the range:

Activecell.Select

22
2. VBA Fundamentals – Collections

▪ Many of Excel’s objects belong to collections. A collection consists of


many similar objects.

▪ Workbooks: All currently-open workbook objects

▪ Charts: All charts contained in a particular workbook

▪ Worksheets: All sheets contained in a particular workbook

23
2. VBA Fundamentals - Collections

▪ If you want to refer to a worksheet in the Worksheets collection, you


can refer to it by its position in the collection as an index number
starting with 1 or by its name as quoted text:

Worksheets(1).Select
Worksheets("Mysheet").Select

▪ You can also use Sheets collection which is a collection of all the
sheets in the specified or active workbook.

24
2. VBA Fundamentals – Properties

▪ Properties are the characteristics of an object. You can refer to the


property of an object by referring to the object and then the property.

▪ Some properties can be changed. For example, you can change the
name of your worksheet by changing its Name property:
Worksheets("Sheet1").Name = "MySheet"

▪ But some properties are read-only. You can’t assign a value to them
directly. For example, index property of a worksheet is read-only.

ActiveSheet.Index

25
2. VBA Fundamentals – Methods

▪ Methods are the actions that can be performed with an object.

▪ Simple examples of an Excel method are the Select method or Copy


method of the Range object:

Range("A1").Select Range("A1").Copy

▪ Some methods have arguments that can dictate how they are
applied. For instance, the Paste method can be used more effectively
by explicitly defining the Destination argument.

ActiveSheet.Paste Destination:=Range("B1")

26
2. VBA Fundamentals – Methods

▪ You can view Properties


and Methods of an object
in Object Browser.

▪ Properties:

▪ Methods:

27
2. VBA Fundamentals – Add Method
▪ How to create a new workseet using VBA?
▪ You can use Add method for Sheets object which has following
syntax:
Sheets. Add([Before],[After],[Count])

▪ Before, After: An object that specifies the sheet before which the
new sheet is added. The default if before.
▪ Count: The number of sheets to be added. The default value is the
number of selected sheets.

▪ The following code creates 3 new worksheets after the active


worksheet:
Sheets.Add After:=ActiveSheet, Count:= 3 28
2. VBA Fundamentals – Methods
▪ How to delete worksheets using VBA?
▪ You can use Delete method for Worksheet object which has following
syntax:
Worksheet_expression.Delete

▪ Worksheet_expression: Refer to a worksheet

▪ The following code delete the active worksheet:


ActiveSheet.Delete

▪ When you delete a Worksheet object, this method displays a dialog


box that prompts the user to confirm the deletion. This dialog box is
displayed by default
29
2. VBA Fundamentals – Methods
▪ How to delete worksheets using VBA?
▪ To delete a worksheet without displaying a dialog box, set the
Application.DisplayAlerts property to False before running the code
▪ The following code delete the active worksheet without displaying a
dialog box:

Application.DisplayAlerts = False: ActiveSheet.Delete

30
2. VBA Fundamentals – Working With Ranges

▪ A Range object is contained in a Worksheet object and consists of a


single cell or range of cells on a single worksheet. There are three
ways of referring to Range objects in your VBA code:

▪ The Range property of a Worksheet or Range class object

▪ The Cells property of a Worksheet object

31
2. VBA Fundamentals – Range Property

▪ You can refer to cells using Range property of a worksheet by


following syntaxes:

▪ The example below puts the value 12.3 into cell A1 on Sheet1:
Worksheets("Sheet1").Range("A1").Value = 12.3

▪ The Range property also recognizes defined names in workbooks. if


a cell is named Input, you can enter a value into that named cell:

Worksheets("Sheet1").Range("Input").Value = 100

32
2. VBA Fundamentals – Range Property

33
2. VBA Fundamentals – Cells Property
▪ Another way to reference a range is to use the Cells property on
worksheet objects. Here the syntaxes:

▪ This example enters the value 9 in cell A1 on Sheet1. In this case,


we’re using the first syntax, which accepts the index number of the
row (from 1 to 1048576) and the index number of the column (from 1
to 16384):

Worksheets("Sheet1").Cells(1, 1) = 9

34
2. VBA Fundamentals – Cells Property
▪ The second syntax of the Cells property uses a single argument that
can range from 1 to 17,179,869,184. This number is equal to the
number of cells in an Excel worksheet. The cells are numbered
starting from A1 and continuing right and then down to the next
row. The 16,384th cell is XFD1; the 16,385th cell is A2 ➪ Do not
recommend to use.
▪ You can also use this syntax with a Range object. In this case, the
cell returned is relative to the Range object referenced.
▪ The third syntax for the Cells property simply returns all cells on the
referenced worksheet.
35
2. VBA Fundamentals – Practice
Practice 8.1. Use Immediate Window to:
1. Enter following data using different methods (Range and Cell
properties) into worksheet 1:

2. Create new worksheets after worksheet 1, where each worksheet's


name corresponds to a customer's name in worksheet 1.
36
2. VBA Fundamentals – Practice
3. Enter following data in the worksheet John in question 2.

4. Copy the data in the worksheet John to the other customers’


worksheets.

37
3. VBA Language Elements
▪ This is an example of a simple procedure, which is stored in a
VBA module, calculates the sum of the first 100 positive integers:

Sub VBA_Demo()
' This is a simple VBA Example
Dim Total As Long, i As Long
Total = 0
For i = 1 To 100
Total = Total + i
Next i
MsgBox Total
End Sub

38
3. VBA Language Elements
▪ Common VBA language elements, including the following:
▪ A comment (the line that begins with an apostrophe).
▪ A variable declaration statement (the line that begins with
Dim).
▪ Two variables (Total and i)
▪ Two assignment statements (Total = 0 and Total = Total + i)
▪ A looping structure (For - Next)
▪ A VBA function (MsgBox)

39
3. VBA Language Elements: Comment

▪ A comment is descriptive text embedded in your code and ignored


by VBA.

▪ A comment is indicated by an apostrophe (symbol ‘ )

▪ It’s a good idea to use comments to describe what you’re doing


because an instruction’s purpose isn’t always obvious.

▪ You can use a complete line for your comment, or you can insert a
comment after an instruction on the same line.

40
3. VBA Language Elements: Comment

▪ The following example shows a VBA procedure with three


comments:

Sub CommentDemo()
' This procedure does nothing of
value
x = 0 'x represents nothingness
' Display the result
MsgBox x
End Sub

41
3. VBA Language Elements: Comment
▪ VBA ignores any text that follows an apostrophe – except when
the apostrophe is contained within quotation marks – up until the
end of the line.

▪ The following are a few general tips on making the best use of
comments:
▪ Describe briefly the purpose of each procedure that you write.
▪ Describe the purpose of variables.
▪ Write comments while you code rather than afterward.

42
4. Variables, Data Types, and Constants – Variables
▪ VBA’s main purpose is to manipulate data. Some data resides in
objects, such as worksheet ranges. Other data is stored in
variables that you create.
▪ A variable is a named storage location used to store data during
the execution of a program.
▪ Few rules regarding variable names:
▪ The first character must be alphabetic.
▪ VBA doesn’t distinguish between case.
▪ You can’t use spaces or periods.
▪ You can’t embed special type declaration characters (#, $, %,
&, or !) in a variable name. 43
4. Variables, Data Types, and Constants – Variables
▪ You assign a value to a variable by using the equal sign “=“ operator.
▪ VBA has many reserved words, which are words that you can’t use
for variable or procedure names. For example: Next, For, With
▪ Examples of assignment expressions that use various types of
variables:
x = 1
InterestRate = 0.075
LoanPayoffAmount = 243089.87
DataEntered = False
x = x + 1
MyNum = YourNum * 1.25
UserName = "Bob Johnson"
DateStarted = #12/14/2012# 44
4. Variables, Data Types, and Constants – Data Types
▪ Data type refers to how data is stored in memory – as integers,
real numbers, strings, and so on.
▪ Although VBA can take care of data typing automatically, it does
so at a cost: slower execution and less efficient use of memory ➪
It is recommended to define the data type for variables used.
▪ When VBA works with data, execution speed is partially a
function of the number of bytes that VBA has at its disposal ➪
The fewer the bytes used by the data, the faster that VBA can
access and manipulate the data.

45
4. Variables, Data Types, and Constants – Declare Variables

▪ If you don’t declare the data type for a variable that you use in a
VBA routine, VBA uses the default data type, Variant. Data stored
as a Variant acts like a chameleon: it changes type, depending on
what you do with it.
▪ The following procedure demonstrates how a variable can
assume different data types:
Sub VariantDemo()
MyVar = True
MyVar = MyVar * 100
MyVar = MyVar / 4
MyVar = "Answer: " & MyVar
MsgBox MyVar
End Sub
46
4. Variables, Data Types, and Constants – Declare Variables
▪ You can use the VBA TypeName function to determine the data
type of a variable. Here’s a modified version of the VariantDemo
procedure. This version displays the data type of MyVar at each
step
Sub VariantDemo3()
MyVar = True
MsgBox TypeName(MyVar)
MyVar = MyVar * 100
MsgBox TypeName(MyVar)
MyVar = MyVar / 4
MsgBox TypeName(MyVar)
MyVar = "Answer: " & MyVar
MsgBox TypeName(MyVar)
MsgBox MyVar
End Sub 47
4. Variables, Data Types, and
Constants – Data Types

48
4. Variables, Data Types, and Constants – Data Types

49
4. Variables, Data Types, and Constants – Declare Variables

▪ To force yourself to declare all variables that you use, include the
following as the first instruction in your VBA module:

▪ When this statement is present, VBA won’t even execute a


procedure if it contains an undeclared variable name.

50
4. Variables, Data Types, and Constants – Constants

▪ A variable’s value may change while a procedure is executing


(that’s why it’s called a variable). Sometimes, you need to refer to a
named value or string that never changes – a constant.
▪ You declare constants with the Const statement:

Const NumQuarters as Integer = 4


Const Rate = .0725, Period = 12
Const ModName as String = "Budget
Macros"

51
4. Variables, Data Types, and Constants – Scoping

▪ A variable’s scope determines in which modules and procedures


you can use the variable.
▪ The table below lists the three ways in which a variable can be
scoped.

52
4. Variables, Data Types, and Constants – Scoping

▪ A local variable is a variable declared within a procedure. The


most common way to declare a local variable is to place a Dim
statement between a Sub statement and an End Sub statement.
▪ The following procedure uses six local variables declared by using
Dim statements:
Sub MySub()
Dim x As Integer
Dim First As Long
Dim InterestRate As Single
Dim TodaysDate As Date
Dim UserName As String
Dim MyValue
' - [The procedure's code goes here] -
End Sub 53
4. Variables, Data Types, and Constants – Scoping

▪ You also can declare several variables with a single Dim


statement. Here’s an example:

Dim x As Integer, y As Integer, z As Integer


Dim First As Long, Last As Double

▪ Sometimes, you want a variable to be available to all procedures


in a module. If so, just declare the variable before the module’s
first procedure:
Dim CurrentValue as Long
Sub Procedure1()
' - [Code goes here] -
End Sub
54
4. Variables, Data Types, and Constants – Scoping

▪ To make a variable available to all the procedures in all the VBA


modules in a project, declare the variable at the module level
(before the first procedure declaration) by using the Public
keyword rather than Dim:

Public CurrentRate as Long

55
5. Assignment Statements

▪ An assignment statement is a VBA instruction that evaluates an


expression and assigns the result to a variable or an object.
▪ VBA uses the equal sign (=) as its assignment operator. The
following are examples of assignment statements:
x = 1
x = x + 1
x = (y * 2) / (z * 2)
FileOpen = True
FileOpen = Not FileOpen
Range("TheYear").Value = 2010

56
5. Assignment Statements

▪ Operators play a major role in VBA.

57
6. Object Variables

▪ An object variable is one that represents an entire object, such as


a range or a worksheet.
▪ Object variables are important for two reasons:
▪ They can simplify your code significantly.
▪ They can make your code execute more quickly.
▪ Object variables, like normal variables, are declared with the Dim
statement.
Dim InputArea As Range

▪ Use the Set keyword to assign an object to the variable.


Set InputArea = Range("C16:E16")
58
6. Object Variables

▪ To see how object variables simplify your code, examine the


following procedure, which doesn’t use an object variable:
Sub NoObjVar()
Worksheets("Sheet1").Range("A1").Value = 124
Worksheets("Sheet1").Range("A1").Font.Bold = True
Worksheets("Sheet1").Range("A1").Font.Italic = True
Worksheets("Sheet1").Range("A1").Font.Size = 14
Worksheets("Sheet1").Range("A1").Font.Name = "Cambria"
End Sub

▪ This routine enters a value into cell A1 of Sheet1 on the active


workbook, applies some formatting, and changes the fonts and
size but it’s required lot of typing and time to run.
59
6. Object Variables

▪ To make your code more efficient, you can condense the routine
with an object variable.

Sub ObjVar()
Dim MyCell As Range
Set MyCell = Worksheets("Sheet1").Range("A1")
MyCell.Value = 124
MyCell.Font.Bold = True
MyCell.Font.Italic = True
MyCell.Font.Size = 14
MyCell.Font.Name = "Cambria"
End Sub

60
Practice
Practice 8.2. Write VBA sub procedures that perform the following
tasks:
1. Sub create_sheets to creates new worksheets after the worksheet 1,
where each worksheet's name corresponds to a customer's name in
worksheet 1. All customer’s worksheets should have the following
loan information.

61
Practice
Them Option Explicit: pha hien loi
Sub create_sheet()
Sheets.Add after:=Worksheets(1),
Count:=3
Sheets(2).name = Worksheets

2. Sub delete_sheets to delete all worksheets except worksheet 1


(1).Range("A2")
Sheets(3).name = Worksheets
(1).Range("A3")
Sheets(4).name = Worksheets

which contains customer’s names. (1).Range("A4")

Sheets(2).Range("A1") = "Type of loan"


Sheets(2).Range("A1") = "Loan

3. Sub declare_variables which performs the following tasks: amount"


Sheets(3).Range("A1") = "Interest rate"
Sheets(4).Range("A1") = "Loan Period"

▪ Declare the suitable types of variable for following data.


Sheets(2).Range("A1:A4").Copy
Sheets(3).Paste Destination:=Sheets
(3).Range("A1:A4")
Sheets(4).Paste Destination:=Sheets

▪ Assign following values to the variables. (4).Range("A1:A4")


End Sub
Sub delete_sheets()
Application.DisplayAlerts = False

▪ Return annual interest (using msgbox function)


Sheets(4).Delete
Sheets(3).Delete
Sheets(2).Delete
End Sub
Sub declare_variable()
Dim name As String
Dim loan_type As String
Dim amount As Double
Dim interest_rate As Double
Dim num_years As Integer

name = "John"
loan_type = "Interest only"
amount = 10000
interest_rate = 0.1
num_years = 10

interest_payment = amount *
interest_rate 62
MsgBox interest_payment
End Sub
7. Built-in Functions

▪ Like most programming languages, VBA has a variety of built-in


functions that simplify calculations and operations.
▪ For example, the VBA Sqr function is equivalent to the Excel SQRT
worksheet function. You use functions in VBA expressions in much
the same way that you use functions in worksheet formulas:
Sub ShowRoot()
Dim MyValue As Double
Dim SquareRoot As Double
MyValue = 25
SquareRoot = Sqr(MyValue)
MsgBox SquareRoot
End Sub
63
7. Built-in Functions

▪ List of functions in VBA: https://learn.microsoft.com/en-


us/office/vba/language/reference/functions-visual-basic-for-
applications
▪ You can use many (but not all) of Excel’s worksheet functions in
your VBA code. The WorksheetFunction object, which is contained
in the Application object, holds all the worksheet functions that you
can call from your VBA procedures. For example:
Application.WorksheetFunction.SumProduct
▪ Keep in mind that you can’t use worksheet functions that have an
equivalent VBA function. For example,
Application.WorksheetFunction.Sqrt(123) will not work 64
7. Built-in Functions – Common Built-in Functions

▪ The Inputbox function displays a prompt in a dialog box, waits for


the user to input text or click a button, and returns a String
containing the contents of the text box.

InputBox(prompt[, title])

▪ Because InputBox function returns a string, you need to declare data


type before using InputBox function.

65
7. Built-in Functions – Common Built-in Functions

▪ The MsgBox function displays a message in a dialog box.


MsgBox(prompt,[buttons],[title])
▪ Prompt: Required. The message displayed in the pop-up display.
▪ Buttons: Optional. A value that specifies which buttons and which
icons, if any, appear in the message box. Use built-in constants —
for example, vbYesNo.
▪ Title: Optional. The text that appears in the message box’s title bar.
The default is Microsoft Excel.

66
7. Built-in Functions – Practice
Practice 8.3. Write sub procedure
inputbox to:
▪ Declare the suitable types of
variable for following data.
▪ Use inputbox built-in function
to ask the user to enter the data.
▪ Store the data entered by the
user to a new worksheet,
naming the worksheet after the
customer's name.
▪ Display the message: “Your annual interest is $800”
67
8. Manipulating Objects – With-End With

▪ As an Excel programmer, you’ll spend a lot of time working with


objects and collections.
▪ Therefore, you want to know the most efficient ways to write your
code to manipulate these objects and collections. VBA offers two
important constructs that can simplify working with objects and
collections:
▪ With-End With constructs
▪ For Each-Next constructs

68
8. Manipulating Objects – With-End With

▪ The With-End With construct enables you to perform multiple


operations on a single object.
▪ To start understanding how the With-End With construct works,
examine the following procedure, which modifies six properties of a
selection’s formatting:
Sub ChangeFont1()
Selection.Font.Name = "Cambria"
Selection.Font.Bold = True
Selection.Font.Italic = True
Selection.Font.Size = 12
Selection.Font.Underline = xlUnderlineStyleSingle
Selection.Font.ThemeColor = xlThemeColorAccent1
End Sub
69
8. Manipulating Objects – With-End With

▪ You can rewrite this procedure using the With-End With construct.
The following procedure performs exactly like the preceding one:
Sub ChangeFont2()
With Selection.Font
.Name = "Cambria"
.Bold = True
.Italic = True
.Size = 12
.Underline = xlUnderlineStyleSingle
.ThemeColor = xlThemeColorAccent1
End With
End Sub
▪ A procedure that uses the With-End With construct to change
several properties of an object can be faster 70
8. Manipulating Objects – Practice
Practice 8.4. Write VBA sub change_format that performs following changes:
▪ Bold for range A1:A5 (Range.Font.Bold = True)
▪ Right allignment for range B1:B5 (Range.HorizontalAlignment =
xlRight)
▪ Solid border for range A1:B5 (Range.Borders.LineStyle =
xlContinuous)
▪ Currency format for the cells B3
(Range. NumberFormat =
“$#,##0.00”)
▪ Autofit for column A and B
(Column.AutoFit)

71
9. Manipulating Collections – For-Next

▪ Suppose you want to perform some action on all objects in a


collection. These occasions are perfect for the For Each-Next
construct because you don’t have to know how many elements are
in a collection to use the For Each-Next construct.
▪ The syntax of the For Each-Next construct:

72
9. Manipulating Collections – For-Next

▪ The following procedure uses the For Each-Next construct with the
Worksheets collection in the active workbook. When you execute
the procedure, the MsgBox function displays each worksheet’s
Name property.
Sub CountSheets()
Dim Item as Worksheet
For Each Item In ActiveWorkbook.Worksheets
MsgBox Item.Name
Next Item
End Sub

73
9. Manipulating Collections – For-Next

▪ VBA provides a way to exit a For-Next loop before all the elements
in the collection are evaluated. Do this with an Exit For statement:
Sub SelectNegative()
Dim Cell As Range
For Each Cell In Range("1:1")
If Cell.Value < 0 Then
Cell.Select
Exit For
End If
Next Cell
End Sub

74
10. Controlling Code Execution

▪ VBA provides a way to exit a For-Next loop before all the elements
in the collection are evaluated. Do this with an Exit For statement:
▪ The preceding section describes the For Each-Next construct, which
is a type of loop.
▪ This section discusses the additional ways of controlling the
execution of your VBA procedures.
▪ If-Then constructs
▪ Select Case constructs
▪ For-Next loops
▪ Do While loops
▪ Do Until loops
75
10. Controlling Code Execution – If-Then Constructs

▪ The basic syntax of the If-Then construct is as follows:

▪ The If-Then construct is used to execute one or more statements


conditionally.

▪ The Else clause is optional. If included, the Else clause lets you
execute one or more instructions when the condition that you’re
testing isn’t True.

76
10. Controlling Code Execution – If-Then Constructs

▪ In the following example, a message is displayed if the time is


before noon.

▪ The time function return the time of computer system. It ranges


from 0 to 1. 0 means 00:00 and 1 means 24:00.

▪ If the current system time is greater than or equal to 0.5 (which


equivalent to 12:00), the procedure ends, and nothing happens.

Sub GreetMe1()
If Time < 0.5 Then MsgBox "Good Morning"
End Sub

77
10. Controlling Code Execution – If-Then Constructs

▪ Another way to code this routine is to use multiple statements, as


follows. However, note that the If statement has a corresponding
End If statement if using multiple statements.

Sub GreetMe1a()
If Time < 0.5 Then
MsgBox "Good Morning"
End If
End Sub

78
10. Controlling Code Execution – If-Then Constructs

▪ If you want to display a different greeting when the time of day is


after noon, add another If-Then statement, as follows:

Sub GreetMe2()
If Time < 0.5 Then MsgBox "Good Morning"
If Time >= 0.5 Then MsgBox "Good Afternoon"
End Sub

▪ Another approach is to use the Else clause of the If-Then construct:


Sub GreetMe3()
If Time < 0.5 Then MsgBox "Good Morning" Else _
MsgBox "Good Afternoon"
End Sub
79
10. Controlling Code Execution – If-Then Constructs

▪ If you need to execute multiple statements based on the condition:

Sub GreetMe3a()
If Time < 0.5 Then
MsgBox "Good Morning"
' Other statements go here
Else
MsgBox "Good Afternoon"
' Other statements go here
End If
End Sub

80
10. Controlling Code Execution – If-Then Constructs

▪ In the following examples, every instruction in the procedure gets


executed, even if the first condition is satisfied.

Sub GreetMe4()
If Time < 0.5 Then MsgBox "Good Morning"
If Time >= 0.5 And Time < 0.75 Then MsgBox "Good Afternoon"
If Time >= 0.75 Then MsgBox "Good Evening"
End Sub

81
10. Controlling Code Execution – If-Then Constructs

▪ A more efficient procedure would include a structure that ends the


routine when a condition is found to be True.

82
10. Controlling Code Execution – If-Then Constructs

▪ Here’s how you can use this syntax to rewrite the GreetMe
procedure:
Sub GreetMe5()
If Time < 0.5 Then
MsgBox "Good Morning"
ElseIf Time >= 0.5 And Time < 0.75
Then
MsgBox "Good Afternoon"
Else
MsgBox "Good Evening"
End If
End Sub

83
10. Controlling Code Execution – If-Then Constructs – Practice

Practice 8.5. Write VBA sub discount with If – Then constructs that
asks the customer to enter the sales amount then returns the
corresponding discount rate. For example, if a customer enters 15, it
will display the message “The discount rate is 15%”

Sales (thousand) Discount (%)


0 to 5 5
5 to 10 10
10 to 30 15
30 to 80 30
More than 80 35
84
10. Controlling Code Execution– Select Case Constructs

▪ The Select Case construct is useful for choosing among three or


more options. This construct also works with two options, and it is
a good alternative to If-Then-Else. The syntax for Select Case is as
follows:

85
10. Controlling Code Execution– Select Case Constructs

▪ The following example of a Select Case construct shows another


way to code the GreetMe examples presented in the preceding
section:
Sub GreetMe()
Dim Msg As String
Select Case Time
Case Is < 0.5
Msg = "Good Morning"
Case 0.5 To 0.75
Msg = "Good Afternoon"
Case Else
Msg = "Good Evening"
End Select
MsgBox Msg
End Sub
86
10. Controlling Code Execution – If-Then Constructs - Practice

Practice 8.6. Write VBA sub discount2 with Select Case constructs that
asks the customer to enter the sales amount then returns the
corresponding discount rate. For example, if a customer enters 15, it
will display the message “The discount rate is 15%”

Sales (thousand) Discount (%)


0 to 5 5
5 to 10 10
10 to 30 15
30 to 80 30
More than 80 35
87
10. Controlling Code Execution– For-Next Loops

▪ Looping is the process of repeating a block of instructions. You


might know the number of times to loop, or the number may be
determined by the values of variables in your program.
▪ The simplest type of a good loop is a For-Next loop. Its syntax is as
follows:

88
10. Controlling Code Execution– For-Next Loops

▪ The following is an example of a For-Next loop that doesn’t use the


optional Step value or the optional Exit For statement. It calculates
the sum of the square roots of the first 100 integers.
Sub SumSquareRoots()
Dim Sum As Double
Dim Count As Integer
Sum = 0
For Count = 1 To 100
Sum = Sum + Sqr(Count)
Next Count
MsgBox Sum
End Sub

89
10. Controlling Code Execution– For-Next Loops

▪ You can also use a Step value to skip some values in the loop. Here’s
the same procedure rewritten to sum the square roots of the odd
numbers between 1 and 100:
Sub SumOddSquareRoots()
Dim Sum As Double
Dim Count As Integer
Sum = 0
For Count = 1 To 100 Step 2
Sum = Sum + Sqr(Count)
Next Count
MsgBox Sum
End Sub

90
10. Controlling Code Execution– For-Next – Practice
Practice 8.7. Write VBA sub create_sheets2 with For-Next loop
construct to create new worksheets, where each worksheet's name
corresponds to a customer's name:

▪ Hint: You can find the last row of column A using following
code: Cells(Rows.Count, 1).End(xlUp).Row

91
10. Controlling Code Execution – For-Next – Practice
Practice 8.8. Write VBA sub delete_sheets2 with For-Next loop
construct to delete all worksheets except the first worksheet:

▪ Hint: You can use Sheets.Count to count to number of


worksheets in the activeworkbook.

92
10. Controlling Code Execution – Do While Loops

▪ Unlike a For- Next loop, a Do While


Loop executes as long as a specified
condition is met.

▪ We use this when we do not know the


number of loops.
▪ The contents of the loop may never be
executed.
93
10. Controlling Code Execution – Do While Loops

▪ The sub below finds the sum of the squares of the first n positive
integers, ensuring the sum does not exceed a specified threshold value.

Sub SumSquare()
Dim n, sum_square, threshold As Integer
threshold = InputBox("Enter threshold value")
sum_square = 0 'To store the sum of square
n = 1 'Initial value
Do While sum_square + n ^ 2 <= threshold
sum_square = sum_square + n ^ 2
n = n + 1
Loop
MsgBox "The sum square of the first " & n - 1 & _
" positive integer numbers is " & sum_square
End Sub
94
10. Controlling Code Execution– Do While Loops

▪ A Do Loop While block is similar to a Do


While Loop, except that in the Do Loop
While loop, the statements contained
within the loop are executed at least once.

95
10. Controlling Code Execution– Do While Loops
▪ The following procedure has the same result as the Sumsquare
procedure, but it uses the second Do While Loop syntax, which
checks the condition at the end of the loop.
Sub SumSquare2()
Dim n, sum_square, threshold As Integer
threshold = InputBox("Enter threshold value")
sum_square = 0 'To store the sum of square
n = 1 'Initial value
Do
sum_square = sum_square + n ^ 2
n = n + 1
Loop While sum_square + n ^ 2 <= threshold
MsgBox "The sum square of the first " & n - 1 & _
" positive integer numbers is " & sum_square
End Sub 96
10. Controlling Code Execution – Do While Loops – Practice

▪ Practice 8.9. Write VBA sub years_to_target with do-while loops


that asks the user to enter the amount of money he has, the annual
interest rate, the amount of money he wants in the future. After
that, the sub should return the number of years needed to achieve
that target. For example, if he has $100,000, the interest rate is 10%,
and he wants $200,000 in the future, it will take him 8 years to
achieve the target.

97
10. Controlling Code Execution– Do Until Loops

▪ The Do Until Loop structure is similar to


the Do While structure. The difference is
In a Do Until Loop, the loop runs while the
condition is False and stops running
when it’s True.

98
10. Controlling Code Execution– Do Until Loops

▪ The Do Loop Until loop is similar to the Do


Until Loop structure except that in the Do
Loop Until, the statements contained
within the loop block are executed at least
once, whether the condition is True or
False.

99
10. Controlling Code Execution– Do Until Loops

▪ The examples that follow perform the same action as the Do While
date entry example in the previous sectiom. For this syntax, the
condition is evaluated at the beginning of the loop.
Sub SumSquare3()
Dim n, sum_square, threshold As Integer
threshold = InputBox("Enter threshold value")
sum_square = 0 'To store the sum of square
n = 1 'Initial value
Do Until sum_square + n ^ 2 > threshold
sum_square = sum_square + n ^ 2
n = n + 1
Loop
MsgBox "The sum square of the first " & n - 1 & _
" positive integer numbers is " & sum_square
End Sub 100
10. Controlling Code Execution– Do Until Loops

▪ The examples that follow perform the same action as the Do While
date entry example in the previous section. For this syntax, the
condition is evaluated at the end of the loop.
Sub SumSquare4()
Dim n, sum_square, threshold As Integer
threshold = InputBox("Enter threshold value")
sum_square = 0 'To store the sum of square
n = 1 'Initial value
Do
sum_square = sum_square + n ^ 2
n = n + 1
Loop Until sum_square + n ^ 2 > threshold
MsgBox "The sum square of the first " & n - 1 & _
" positive integer numbers is " & sum_square
End Sub 101
10. Controlling Code Execution– Do Until Loops – Practice

Practice 8.10. Write VBA sub years_to_target2 with Do Until Loop that
asks the user to enter the amount of money he has, the annual interest
rate, the amount of money he wants in the future. After that, the sub
should return the number of years needed to achieve that target. For
example, if he has $100,000, the interest rate is 10%, and he wants
$200,000 in the future, the sub should return “You need 8 years to
achieve the target, and you will have $214,000”

102

You might also like