100% found this document useful (4 votes)
71 views

Download full EXCEL VBA Programming By Examples Programming For Complete Beginners Step By Step Illustrated Guide to Mastering Excel VBA Thanh Tran ebook all chapters

Guide

Uploaded by

nattiamayic
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
71 views

Download full EXCEL VBA Programming By Examples Programming For Complete Beginners Step By Step Illustrated Guide to Mastering Excel VBA Thanh Tran ebook all chapters

Guide

Uploaded by

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

Experience Seamless Full Ebook Downloads for Every Genre at textbookfull.

com

EXCEL VBA Programming By Examples Programming For


Complete Beginners Step By Step Illustrated Guide
to Mastering Excel VBA Thanh Tran

https://textbookfull.com/product/excel-vba-programming-by-
examples-programming-for-complete-beginners-step-by-step-
illustrated-guide-to-mastering-excel-vba-thanh-tran/

OR CLICK BUTTON

DOWNLOAD NOW

Explore and download more ebook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Excel data analysis by examples Excel data analysis for


complete beginners Step By Step Illustrated Guide to
Mastering Excel data analysis Excel advance Book 1 Thanh
Tran
https://textbookfull.com/product/excel-data-analysis-by-examples-
excel-data-analysis-for-complete-beginners-step-by-step-illustrated-
guide-to-mastering-excel-data-analysis-excel-advance-book-1-thanh-
tran/
textboxfull.com

Excel VBA Programming For Dummies 5th Edition Michael


Alexander

https://textbookfull.com/product/excel-vba-programming-for-
dummies-5th-edition-michael-alexander/

textboxfull.com

Programming Excel with VBA A Practical Real World Guide


Flavio Morgado

https://textbookfull.com/product/programming-excel-with-vba-a-
practical-real-world-guide-flavio-morgado/

textboxfull.com

Essential Excel 2019: A Step-By-Step Guide David Slager

https://textbookfull.com/product/essential-excel-2019-a-step-by-step-
guide-david-slager/

textboxfull.com
Excel 2019 Pivot Tables & Introduction To Dashboards The
Step-By-Step Guide 3rd Edition Benton

https://textbookfull.com/product/excel-2019-pivot-tables-introduction-
to-dashboards-the-step-by-step-guide-3rd-edition-benton/

textboxfull.com

SQL Easy SQL Programming Database Management for Beginners


Your Step By Step Guide to Learning the SQL Database Felix
Alvaro
https://textbookfull.com/product/sql-easy-sql-programming-database-
management-for-beginners-your-step-by-step-guide-to-learning-the-sql-
database-felix-alvaro/
textboxfull.com

Web Development for beginners Learn HTML CSS Javascript


step by step with this Coding Guide Programming Guide for
beginners Website development 1st Edition Mastery
https://textbookfull.com/product/web-development-for-beginners-learn-
html-css-javascript-step-by-step-with-this-coding-guide-programming-
guide-for-beginners-website-development-1st-edition-mastery/
textboxfull.com

Python Programming A Step By Step Guide From Beginner To


Advance Second Edition Eddison

https://textbookfull.com/product/python-programming-a-step-by-step-
guide-from-beginner-to-advance-second-edition-eddison/

textboxfull.com

Learn to Program with Python 3: A Step-by-Step Guide to


Programming Irv Kalb

https://textbookfull.com/product/learn-to-program-with-
python-3-a-step-by-step-guide-to-programming-irv-kalb/

textboxfull.com
EXCEL VBA Programming By
Examples
P rogramming F or C omplete B eginners , S tep -B y -S tep
I llustrated G uide to M astering E xcel VBA

thanh tran
Copyright © 2019 by Thanh Tran
Table of Contents

Chapter 1. Create a Macro


Chapter 2. MsgBox
Chapter 3. Workbook and Worksheet Object
Chapter 4. Range Object
Chapter 5. Variables
Chapter 6. If Then Statement
Chapter 7. Loop
Chapter 8. Macro Errors
Chapter 9. String Manipulation
Chapter 10. Date and Time
Chapter 11. Events
Chapter 12. Array
Chapter 13. Function and Sub
Chapter 14. Application Object
Chapter 15. ActiveX Controls
Chapter 16. Userform
Chapter 1. Create a Macro
Swap Values, Run Code from a Module, Macro Recorder, Use Relative
References, FormulaR1C1, Add a Macro to the Toolbar, Macro
Security, Protect Macro.
Swap Values
This example teaches you how to swap two values in Excel VBA. You will often
need this structure in more complicated programs as we will see later.
Situation:
Two values on your worksheet.

Place a command button on your worksheet and add the following code lines:
1. First, we declare a variable called temp of type Double.
Dim temp As Double
2. We initialize the variable temp with the value of cell A1.
temp = Range("A1").Value
3. Now we can safely write the value of cell B1 to cell A1 (we have stored the
value of cell A1 to temp so we will not lose it).
Range("A1").Value = Range("B1").Value
4. Finally, we write the value of cell A1 (written to temp) to cell B1.
Range("B1").Value = temp
5. Click the command button two times.
Result:
Run Code from a Module
As a beginner to Excel VBA, you might find it difficult to decide
where to put your VBA code. The Create a Macrochapter illustrates
how to run code by clicking on a command button. This example
teaches you how to run code from a module.
1. Open the Visual Basic Editor.
2. Click Insert, Module.

3. Create a procedure (macro) called Cyan.


Sub Cyan()

End Sub
Note: a procedure is either a sub or a function. Learn more
about functions and subs here, if you like.
4. The sub changes the background color of your worksheet to cyan.
To achieve this, add the following code line.
Cells.Interior.ColorIndex = 28
Note: instead of ColorIndex number 28 (cyan), you can use any
ColorIndex number.
To run the procedure, execute the following steps.
5. Click Macros.

6. Select Cyan and click Run.

Result:
Note: code placed into a module is available to the whole workbook.
That means, you can select Sheet2 or Sheet3 and change the
background color of these sheets as well. The Add a Macro to the
Toolbar program illustrates how to make a macro available to all
your workbooks (Excel files). Remember, code placed on a sheet
(assigned to a command button) is only available for that particular
sheet.
Macro Recorder
he Macro Recorder, a very useful tool included in Excel VBA,
records every task you perform with Excel. All you have to do is
record a specific task once. Next, you can execute the task over and
over with the click of a button. The Macro Recorder is also a great
help when you don't know how to program a specific task in Excel
VBA. Simply open the Visual Basic Editor after recording the task to
see how it can be programmed.
Unfortunately, there are a lot of things you cannot do with the Macro
Recorder. For example, you cannot loop through a range of data with
the Macro Recorder. Moreover, the Macro Recorder uses a lot more
code than is required, which can slow your process down.

Record a Macro
1. On the Developer tab, click Record Macro.

2. Enter a name.
3. Select This Workbook from the drop-down list. As a result, the
macro will only be available in the current workbook.
Note: if you store your macro in Personal Macro Workbook, the
macro will be available to all your workbooks (Excel files). This is
possible because Excel stores your macro in a hidden workbook that
opens automatically when Excel starts. If you store your macro in
New Workbook, the macro will only be available in an automatically
new opened workbook.
4. Click OK.
5. Right mouse click on the active cell (selected cell). Be sure not to
select any other cell! Next, click Format Cells.
6. Select Percentage.
7. Click OK.
8. Finally, click Stop Recording.

Congratulations. You've just recorded a macro with the Macro


Recorder!
Run a Recorded Macro
Now we'll test the macro to see if it can change the number format
to Percentage.
1. Enter some numbers between 0 and 1.
2. Select the numbers.

3. On the Developer tab, click Macros.


4. Click Run.

Result:
See the Macro
To take a look at the macro, open the Visual Basic Editor.

Note: the macro has been placed into a module called Module1.
Code placed into a module is available to the whole workbook. That
means, you can select Sheet2 or Sheet3 and change the number
format of cells on these sheets as well. Remember, code placed on a
sheet (assigned to a command button) is only available for that
particular sheet.
Use Relative References
By default, Excel records macros in absolute mode. However,
sometimes it is useful to record macros in relative mode. This
program teaches you how to do this. If you don't know how
to record a macro, we highly recommend you to read this example
first.

Recording in Absolute Mode


To record a macro in absolute mode, execute the following steps.
1. First, click Record Macro.
2. Next, select cell B3. Type Sales and press enter.
3. Type Production and press enter.
4. Type Logistics and press enter.
Result:

5. Click Stop Recording.


6. Empty Range("B3:B5").
7. Select any cell on the sheet and run the recorded macro.
Result:

A macro recorded in absolute mode always produces the same


result.

Recording in Relative Mode


Wouldn't it be nice to place these words anywhere on the sheet
automatically? Not just Range("B3:B5"). This would make the macro
much more flexible. Solution: record the macro in relative mode.
1. Select "Use Relative References".
2. First, select any single cell (for example, cell B8).
3. Next, click Record Macro.
4. Type Sales and press enter.
5. Type Production and press enter.
6. Type Logistics and press enter.
Result:

7. Click Stop Recording.


8. Select any other cell (for example, cell D4) and run the recorded
macro.
Result:
Excel places the words relative to the initial selected cell. That's why
it's called recording in relative mode.
FormulaR1C1
This example illustrates the difference
between A1, R1C1 and R[1]C[1] style in Excel VBA.
1. Place a command button on your worksheet and add the following
code line (A1 style):
Range("D4").Formula = "=B3*10"
Result:

2. Add the following code line (R1C1 style):


Range("D4").FormulaR1C1 = "=R3C2*10"
Result:

Explanation: cell D4 references cell B3 (row 3, column 2). This is an


absolute reference ($ symbol in front of the row number and column
letter).
3. Add the following code line (R[1]C[1] style):
Range("D4").FormulaR1C1 = "=R[-1]C[-2]*10"
Result:
Explanation: cell D4 references cell B3 (one row above and 2
columns to the left). This is a relative reference. This code line gives
the exact same result as the code line used at step 1.
4. Why learning about this? Because the Macro Recorder uses the
FormulaR1C1 property (R[1]C[1] style). The Macro Recorder creates
the following code lines if you enter the formula =B3*10 into cell D4.

Explanation: you can see that this is the exact same code line used
at step 3.
Add a Macro to the Toolbar
If you use an Excel macro frequently, you can add it to the Quick
Access Toolbar. This way you can quickly access your macro. First,
we record an empty macro.
1. On the Developer tab, click Record Macro.

2. Name the macro MyName. Choose to store the macro in Personal


Macro Workbook. This way the macro will be available to all your
workbooks (Excel files). This is possible because Excel stores your
macro in a hidden workbook that opens automatically when Excel
starts.
3. Click Stop Recording.

4. Open the Visual Basic Editor.


5. Create the macro:
This macro places your name in the Active Cell.
6. Now we can add this macro to the Quick Access Toolbar. Right
click the Quick Access Toolbar and select Customize Quick Access
Toolbar.

7. Under Choose commands, select Macros.


8. Select the macro and click Add.
9. You can modify the button that will be added to the Quick Access
Toolbar by clicking on Modify. For example, choose a smiley.
10. Click OK.
11. You can now execute the macro by clicking on the smiley button
added to the Quick Access Toolbar.
Result:
Exploring the Variety of Random
Documents with Different Content
License. You must require such a user to return or destroy all
copies of the works possessed in a physical medium and
discontinue all use of and all access to other copies of Project
Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™


electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except


for the “Right of Replacement or Refund” described in paragraph
1.F.3, the Project Gutenberg Literary Archive Foundation, the owner
of the Project Gutenberg™ trademark, and any other party
distributing a Project Gutenberg™ electronic work under this
agreement, disclaim all liability to you for damages, costs and
expenses, including legal fees. YOU AGREE THAT YOU HAVE NO
REMEDIES FOR NEGLIGENCE, STRICT LIABILITY, BREACH OF
WARRANTY OR BREACH OF CONTRACT EXCEPT THOSE
PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE THAT THE
FOUNDATION, THE TRADEMARK OWNER, AND ANY
DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE
TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL,
PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE
NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of receiving it,
you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or entity
that provided you with the defective work may elect to provide a
replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.

1.F.4. Except for the limited right of replacement or refund set forth in
paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the


Foundation, the trademark owner, any agent or employee of the
Foundation, anyone providing copies of Project Gutenberg™
electronic works in accordance with this agreement, and any
volunteers associated with the production, promotion and distribution
of Project Gutenberg™ electronic works, harmless from all liability,
costs and expenses, including legal fees, that arise directly or
indirectly from any of the following which you do or cause to occur:
(a) distribution of this or any Project Gutenberg™ work, (b)
alteration, modification, or additions or deletions to any Project
Gutenberg™ work, and (c) any Defect you cause.

Section 2. Information about the Mission of


Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a
secure and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help,
see Sections 3 and 4 and the Foundation information page at
www.gutenberg.org.
Section 3. Information about the Project
Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg
Literary Archive Foundation are tax deductible to the full extent
permitted by U.S. federal laws and your state’s laws.

The Foundation’s business office is located at 809 North 1500 West,


Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact

Section 4. Information about Donations to


the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many small
donations ($1 to $5,000) are particularly important to maintaining tax
exempt status with the IRS.

The Foundation is committed to complying with the laws regulating


charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where


we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make


any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.

Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.

Section 5. General Information About Project


Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.

Project Gutenberg™ eBooks are often created from several printed


editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like