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

Brainalyst's VBA For Macros Guide

Uploaded by

lsbexcel
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)
32 views

Brainalyst's VBA For Macros Guide

Uploaded by

lsbexcel
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/ 71

ALLYOU

NEED TO
KNOW SERIES
T
oBe
comeaS
ucc
ess
ful
Dat
aPr
ofe
ssi
ona
l

V
BAF
ORMA
CRO
S
ABOUT BRAINALYST

Brainalyst is a pioneering data-driven company dedicated to transforming data into actionable insights and
innovative solutions. Founded on the principles of leveraging cutting-edge technology and advanced analytics,
Brainalyst has become a beacon of excellence in the realms of data science, artificial intelligence, and machine
learning.

OUR MISSION

At Brainalyst, our mission is to empower businesses and individuals by providing comprehensive data solutions
that drive informed decision-making and foster innovation. We strive to bridge the gap between complex data and
meaningful insights, enabling our clients to navigate the digital landscape with confidence and clarity.

WHAT WE OFFER

1. Data Analytics and Consulting


Brainalyst offers a suite of data analytics services designed to help organizations harness the power of their
data. Our consulting services include:

• Data Strategy Development: Crafting customized data strategies aligned with your business
objectives.

• Advanced Analytics Solutions: Implementing predictive analytics, data mining, and statistical
analysis to uncover valuable insights.

• Business Intelligence: Developing intuitive dashboards and reports to visualize key metrics and
performance indicators.

2. Artificial Intelligence and Machine Learning


We specialize in deploying AI and ML solutions that enhance operational efficiency and drive innovation.
Our offerings include:

• Machine Learning Models: Building and deploying ML models for classification, regression,
clustering, and more.

• Natural Language Processing: Implementing NLP techniques for text analysis, sentiment analysis,
and conversational AI.

• Computer Vision: Developing computer vision applications for image recognition, object detection,
and video analysis.

3. Training and Development


Brainalyst is committed to fostering a culture of continuous learning and professional growth. We provide:

• Workshops and Seminars: Hands-on training sessions on the latest trends and technologies in
data science and AI.

• Online Courses: Comprehensive courses covering fundamental to advanced topics in data


analytics, machine learning, and AI.

• Customized Training Programs: Tailored training solutions to meet the specific needs of
organizations and individuals.

2021-2024
4. Generative AI Solutions

As a leader in the field of Generative AI, Brainalyst offers innovative solutions that create new content and
enhance creativity. Our services include:

• Content Generation: Developing AI models for generating text, images, and audio.

• Creative AI Tools: Building applications that support creative processes in writing, design, and
media production.

• Generative Design: Implementing AI-driven design tools for product development and
optimization.

OUR JOURNEY

Brainalyst’s journey began with a vision to revolutionize how data is utilized and understood. Founded by
Nitin Sharma, a visionary in the field of data science, Brainalyst has grown from a small startup into a renowned
company recognized for its expertise and innovation.

KEY MILESTONES:

• Inception: Brainalyst was founded with a mission to democratize access to advanced data analytics and AI
technologies.

• Expansion: Our team expanded to include experts in various domains of data science, leading to the
development of a diverse portfolio of services.

• Innovation: Brainalyst pioneered the integration of Generative AI into practical applications, setting new
standards in the industry.

• Recognition: We have been acknowledged for our contributions to the field, earning accolades and
partnerships with leading organizations.

Throughout our journey, we have remained committed to excellence, integrity, and customer satisfaction.
Our growth is a testament to the trust and support of our clients and the relentless dedication of our team.

WHY CHOOSE BRAINALYST?

Choosing Brainalyst means partnering with a company that is at the forefront of data-driven innovation. Our
strengths lie in:

• Expertise: A team of seasoned professionals with deep knowledge and experience in data science and AI.

• Innovation: A commitment to exploring and implementing the latest advancements in technology.

• Customer Focus: A dedication to understanding and meeting the unique needs of each client.

• Results: Proven success in delivering impactful solutions that drive measurable outcomes.

JOIN US ON THIS JOURNEY TO HARNESS THE POWER OF DATA AND AI. WITH BRAINALYST, THE FUTURE IS
DATA-DRIVEN AND LIMITLESS.

2021-2024
Preface
Welcome to “Excel VBA Basic to Advance,” a comprehensive guide that bridges the gap between
rudimentary spreadsheet skills and the robust programming capabilities of Visual Basic for Appli-
cations (VBA). Authored by Nitin Sharma, the Founder and CEO of Brainalyst, this book embodies
the principles and practices of a data-driven company deeply rooted in leveraging analytical prow-
ess to foster decision-making and efficiency across various industries.

At Brainalyst, we believe in the power of data to transform ordinary insights into extraordinary
outcomes. This guide is an extension of our commitment to empower professionals by demys-
tifying the complexities of Excel VBA. Whether you are a novice eager to learn the basics or an
advanced user looking to refine your programming skills, this book offers a structured pathway to
mastering VBA.

“Excel VBA Basic to Advance” is designed to be both a learning tool and a practical resource,
providing readers with detailed explanations, step-by-step tutorials, and real-world applications
of VBA. From automating routine tasks to creating complex user-defined functions and macros,
the techniques discussed herein are tailored to enhance productivity and expand the analytical
capabilities of Excel users.

This book is a culmination of rigorous research, practical experience, and the collaborative spirit
of Brainalyst. As we navigate through the pages, you will encounter a blend of theory and prac-
tice, each complementing the other to provide a holistic understanding of VBA programming. Our
aim is not just to impart knowledge, but to inspire innovation and efficiency through the powerful
platform of Excel VBA.

Copyright 2021-2024, Brainalyst - All rights reserved. No part of this publication may be repro-
duced, distributed, or transmitted in any form or by any means, including photocopying, record-
ing, or other electronic or mechanical methods, without the prior written permission of the pub-
lisher, except in the case of brief quotations embodied in critical reviews and certain other
noncommercial uses permitted by copyright law.

We are excited to accompany you on this journey of discovery and mastery of Excel VBA. Let’s
transform potential into performance, one macro at a time.

Nitin Sharma Founder/CEO, Brainalyst

2021-2024
TABLE OF CONTENTS
1. Introduction to VBA 8. Advanced VBA Techniques
• What is VBA? • Error Handling in VBA
• History of VBA • Creating UserForms
• Interacting with Other Applications
2. Key Aspects of VBA • Advanced Data Handling and Analysis
• Integration with Microsoft Office
• Event-Driven Programming 9. Automation with Macros
• Object-Oriented Features • Recording Macros
• Macro Recorder and its Utilities • Understanding Recorded VBA Code
• Extensibility Features • Editing and Optimizing Macros

3. Enabling VBA in Excel 10.Creating Custom Functions


• Enabling Developer Tab in Excel Versions • Writing and Using Custom VBA Functions
• Accessing VBA Editor • Utilizing Arrays and Collections

4. Navigating the VBA Environment 11.Debugging and Error Handling


• Understanding the Visual Basic Editor • Common Debugging Techniques
• Project Window and Properties • Using Immediate Window and Watch
• Using the Code Window Window
• Modules and Forms in VBA • Handling Runtime Errors

5. Writing Your First VBA Code 12.VBA Best Practices


• Modules: Creating and Managing • Writing Clean and Readable Code
• Writing Procedures and Functions • Optimizing VBA for Performance
• Understanding Sub and Function • Security Practices in VBA Programming
Procedures
• Declaring Variables and Data Types 13.Applications of VBA
• Automating Repetitive Tasks
6. Working with Excel Objects in VBA • Creating Complex Formulas
• Range, Cells, Rows, and Columns • Developing Interactive Tools
• Working with Excel Worksheets and
Workbooks 14.Appendix
• Manipulating Data Using VBA • VBA Code Examples
• VBA Functions Quick Reference
7. Using Conditional Logic and Loops • Troubleshooting Common VBA Errors
• If...Then...Else Statements
• For...Next Loops
• Do Loops and While Loops

Disclaimer: This material is protected under copyright act Brainalyst © 2021-2024. Unauthorized use and/ or
duplication of this material or any part of this material including data, in any form without explicit and written
permission from Brainalyst is strictly prohibited. Any violation of this copyright will attract legal actions.

2021-2024
INTRODUCTION TO EXCEL VBA: MASTERING AUTOMATION AND EFFICIENCY
Welcome to the World of Excel VBA
Visual Basic for Applications (VBA) is a powerful scripting language provided by Microsoft to automate tasks and
extend the capabilities of Excel and other Office applications. VBA offers a robust environment where you can
build user-defined functions, automate repetitive tasks, and create complex macros that streamline your work-
flows. Whether you are a finance professional needing to automate reports, a data analyst looking to streamline
your data processing, or an Excel enthusiast eager to learn more about Excel’s capabilities, mastering VBA will
elevate your productivity and efficiency.

What You Will Learn


This guide, “Excel VBA Basic to Advance,” is designed to take you from a basic understanding of VBA to ad-
vanced techniques that will allow you to harness the full power of automation and customization in Excel. You
will start by learning the fundamentals of VBA, including its history and key concepts. As you progress, you will
delve deeper into the VBA programming environment, learn to write and debug your own scripts, and discover
how to create interactive forms and automate repetitive tasks.

Structure of This Guide


This guide is structured to provide a step-by-step approach to learning Excel VBA:

1. Introduction to VBA: Begin with what VBA is, its significance, and its historical context.
2. Setting Up: Learn how to enable VBA in Excel, access the VBA editor, and navigate its features.
3. Basic VBA Programming: Understand how to write basic VBA code, including subroutines, functions, and
handling Excel objects like cells, ranges, and sheets.
4. Advanced VBA Features: Explore more complex aspects of VBA, such as creating user forms, handling
errors, and using advanced data structures like arrays.
5. Practical Applications: See how VBA can be applied to solve real-world problems, automate tasks, and
enhance Excel’s functionality.

How to Use This Guide


To get the most out of this guide, engage with the provided examples, exercises, and best practices. Start by read-
ing each section, then practice writing the VBA code in your own Excel environment. Use the troubleshooting
and debugging tips to solve common issues, and don’t hesitate to refer back to earlier sections for a refresher as
needed.

Embrace the Power of Automation


As you embark on this journey to becoming proficient in Excel VBA, remember that the goal is to enhance your
ability to automate and customize Excel to suit your needs. The skills you develop will not only save you time but
also open up new possibilities for data analysis and report generation. Welcome to the transformative power of
Excel VBA!

2021-2024
BRAINALYST - VBA SERIES

Excel VBA Basic to Advance


VBA (Visual Basic for Applications)
What is VBA?
• Visual Basic for Applications (VBA) is a programming language developed by Microsoft. It serves as
a scripting language for automating tasks and building custom functionality within Microsoft Office
applications, including Excel, Word, Outlook, and Access. VBA enables users to create macros, which
are small programs that automate repetitive actions, making it a powerful tool for enhancing pro-
ductivity and efficiency in Office environments.

• History of VBA:
• 1985-1990: Origins of Visual Basic:
• Microsoft introduced Visual Basic (VB) as a programming language and integrated devel-
opment environment (IDE) for building Windows applications. The initial version, VB 1.0,
was released in 1991.

• 1993: Introduction of VBA:


• Microsoft introduced VBA with the release of Microsoft Excel 5.0. It allowed users to auto-
mate repetitive tasks and create custom functions within Excel. VBA was later integrated
into other Microsoft Office applications.

• 1998: Office 2000:


• VBA became an integral part of Office 2000, providing a unified scripting language across
various Office applications, including Excel, Word, Outlook, and Access.

• 2007: Office Open XML Formats:


• With the introduction of Office Open XML formats (.xlsx, .docx, .pptx), VBA continued to
play a crucial role in automating and customizing the new Office file formats.

• 2013: Introduction of Apps for Office:


• Microsoft introduced “Apps for Office” to extend Office functionality. These apps could be
built using various technologies, including VBA.

• 2016: Excel JavaScript API:


• Excel started supporting JavaScript APIs for building add-ins, providing an alternative to
VBA for certain scenarios. VBA, however, remained a primary choice for many users due
to its familiarity.

• 2018: Office Scripts in Excel Online:


• Microsoft introduced Office Scripts, a new automation feature in Excel Online. While it
complements VBA, it is designed to run in the cloud.

• Present: Ongoing Updates:


• VBA remains a powerful tool for Excel automation, and Microsoft continues to support
• and update it. It coexists with newer technologies, providing flexibility for developers.

Pg. No.1 2021-2024


BRAINALYST - VBA SERIES

• Key Aspects of VBA:


• Embedded within Applications:
• VBA is integrated into Microsoft Office applications, allowing users to write code that
directly interacts with the features and data of the application.

• Event-Driven:
• It follows an event-driven programming model, where actions or events trigger the exe-
cution of specific code. For example, clicking a button or opening a workbook can trigger
VBA code.

• Object-Oriented:
• VBA is an object-oriented programming language, meaning it revolves around manipulat-
ing objects. In Excel, objects can be ranges, worksheets, charts, etc.

• Macro Recorder:
• VBA includes a Macro Recorder that allows users to record their actions in an Office appli-
cation and automatically generates VBA code based on those actions.

• Extensibility:
• VBA provides extensibility by allowing users to create custom functions, automate com-
plex tasks, and build user interfaces using forms.

• What is Visual Basic (VB)?


• Visual Basic (VB), without the “for Applications,” refers to a standalone programming lan-
guage developed by Microsoft. VB was originally designed for building Windows appli-
cations and had its own separate IDE (Integrated Development Environment). It shares
syntactical similarities with VBA but is a distinct language.

• Why Use VBA?


• Automation:
• Automate repetitive and time-consuming tasks, reducing manual effort.

• Customization:
• Customize Excel and other Office applications to meet specific needs.

• Enhanced Functionality:
• Extend the functionality of Office applications by creating custom features.

• Efficiency:
• Improve workflow efficiency by streamlining processes and eliminating manual steps.

• Interactivity:
• Create interactive user interfaces, forms, and dashboards within Excel.

• Data Manipulation:
• Perform complex data manipulation, analysis, and reporting.

Enable Developer Tab in Excel:


• Step 1: Open Excel Options: 2007
• Click on the Microsoft Office Button (round button at the top-left corner).
• Select “Excel Options” at the bottom.

2021-2024 Pg. No.2


BRAINALYST - VBA SERIES

• Step 2: Access Popular Options


• In the Excel Options window, navigate to the “Popular” category on the left.

Pg. No.3 2021-2024


BRAINALYST - VBA SERIES

• Step 3: Check “Show Developer tab in the Ribbon”


• Look for the “Top options for working with Excel” section.
• Check the box next to “Show Developer tab in the Ribbon.”

• Step 4: Confirm and Close


• Click “OK” to confirm your selection and close the Excel Options window.
• After completing these steps, the Developer tab will now appear in the Excel Ribbon.

Enable Developer Tab in Excel 2010:


• Step 1: Access Excel Options
• Click on the “File” tab in the ribbon to go to the Backstage view.
• Click on “Options” at the bottom of the list.

• Step 2: Open Customize Ribbon Section


• In the Excel Options window, click on “Customize Ribbon” on the left sidebar.

• Step 3: Check “Developer” Option


• On the right side of the Excel Options window, you’ll see a list of Main tabs.
• Check the box next to “Developer” to enable it.

• Step 4: Confirm and Close


• Click “OK” to confirm your changes and close the Excel Options window.

• Now, you should see the Developer tab in the Excel Ribbon.

2021-2024 Pg. No.4


BRAINALYST - VBA SERIES

How to Open the VBA Editor (Alt + F11)


• Open Excel:
• Launch Microsoft Excel on your computer.

• Access the Developer Tab:


• If the “Developer” tab is not visible in the ribbon, enable it:
• Go to File > Options.
• In the Excel Options dialog, select Customize Ribbon.
• Check the “Developer” option and click “OK.”

• Open the VBA Editor:


• Once the Developer tab is visible:
• Go to the “Developer” tab.
• Click on the “Visual Basic” icon (or press Alt + F11).

The Look of the Visual Basic Editor

• To begin writing VBA code in Excel, you need to use the Visual Basic Editor (VBE).
Here’s a detailed exploration of the key elements within the VBE:
• Shortcut Key: Alt + F11

• Project Window:
• Microsoft Objects:
• Contains a code area for your workbook (ThisWorkbook) and your worksheets.
• This area includes Microsoft Excel objects like Workbook, Worksheet, and other proj-
ect-related items.

• Forms:
• Stores any user forms that you create. User forms are custom dialog boxes you can design
to interact with users.

• Modules:
• Stores macros and user-defined functions that you create. Modules are where you write
and store VBA code.

• Properties Window:
• Allows you to modify properties of objects, forms, and modules.
• When an object, form, or module is selected, its properties can be viewed and modified in
this window.

Pg. No.5 2021-2024


BRAINALYST - VBA SERIES

• Code Window:
• The area where you write and edit Visual Basic code.

• I. Module (Where Code is Written):


• Module Overview:
• Definition: A module is a container for organizing and storing VBA code in the
Visual Basic Editor (VBE).
• Purpose: It provides a designated space where you can write, store, and manage
your VBA code.

• Types of Modules:
• Standard Module:
• Stores macros and user-defined functions.
• Created by going to Insert > Module in the VBE.

• Class Module:
• Used for creating custom objects and their associated procedures.
• Advanced concept often employed in object-oriented programming.

• Instructions to View a Module:


• In the VBE:
• Open the Visual Basic Editor by pressing ALT + F11.
• In the Project Explorer window, find and double-click on the module
you want to view.
• To insert a module, go to Insert > Module.
• The module opens in the Code Window, displaying its content.

2021-2024 Pg. No.6


BRAINALYST - VBA SERIES

• Code in a Module:
• The actual VBA code is written within a module.
• Examples of code within a module include Sub Procedures, Function Procedures, and
other VBA statements.
• Modules serve as organized units for grouping related code.

Pg. No.7 2021-2024


BRAINALYST - VBA SERIES

• Sub Procedures:
• Definition:
• A Sub Procedure (Subroutine) is a set of VBA code that performs a specific task or a
sequence of tasks in Excel.
• Named with a macro name following the Sub keyword.
• Displays the code for the selected object, form, or module.
• Code is written in procedures (Sub and Function).

• Sub Keyword:
• Indicates the start of a Sub Procedure.

• Macro Name:
• The name you give to your Sub Procedure. Follows the Sub keyword.
• Should be unique and meaningful, reflecting the task performed.

• Code Block:
• The area between Sub and End Sub where you write your VBA code.
• This is where you specify the actions Excel should perform.
• (): Parentheses that may contain parameters (empty in this example).
• End Sub: Keyword to mark the end of the Sub Procedure.

• Execution:
• To execute a Sub Procedure:
• Go to the Excel workbook.
• Press ALT + F8 to open the Macro dialog.
• Select the desired macro and click “Run.”

• Purpose of Sub Procedures:


• Sub Procedures encapsulate specific tasks, making your code modular and easy to man-
age.
• By breaking down tasks into smaller Sub Procedures, you can achieve more modular and
maintainable code.

Variable Data Types:

• Variable is a symbolic name given to a memory location that stores data. Variables are fundamental
to any programming language, and they play a crucial role in storing, manipulating, and retrieving
values within a program.

• 1. Declaring Variables:
• In VBA, declaring a variable involves specifying the data type it will hold and giving it a
name.

• Key Points about Variables in VBA:


• Declaration:
• Declaring a variable in VBA involves specifying its data type and name.

2021-2024 Pg. No.8


BRAINALYST - VBA SERIES

• Data Types:
• VBA supports various data types such as Integer, Double, String, Date, Boolean, Curren-
cy, Object, and Variant.
• Choosing the appropriate data type is essential for efficient memory usage and prevent-
ing data-related errors.

• Data Types:
• i. Numeric Types:
• Byte: Holds whole numbers from 0 to 255.
• Integer: Holds whole numbers from -32,768 to 32,767.
• Long: Holds whole numbers from -2,147,483,648 to 2,147,483,647.
• Single: Holds single-precision floating-point numbers.
• Double: Holds double-precision floating-point numbers.
• Currency: Holds currency values with four decimal places.

• Date: Holds date and time values.

• Boolean: Holds True or False values.

• Other Types:
• Object: Holds references to objects (e.g., Worksheet, Range).
• Variant: Holds any type of data.

• Scope:
• Local Variables: Declared within a specific procedure and are accessible only with-
in that procedure.
• Module-Level Variables: Declared at the module level and are accessible to all pro-
cedures within that module.
• Global Variables: Declared at the project level and are accessible across all modules
in the project.

Pg. No.9 2021-2024


BRAINALYST - VBA SERIES

• Naming Conventions:
• Follow a consistent naming convention to make your code more readable.
• Use descriptive names that convey the purpose of the variable.
• Examples:

• Initialization:
• Variables can be initialized (assigned an initial value) at the time of declaration.
• Example:

• Constants:
• Constants are variables with fixed values that cannot be changed during the
execution of the program.
• Declared using the Const keyword.
• Example:

• Arrays:
• Declare arrays to store multiple values under a single variable name.

Recording Macros
• Recording macros in Excel VBA is a convenient way to automate repetitive tasks by generating VBA
code based on your actions in Excel.

• Steps:
• Enable Developer Tab:
• If you haven’t already, enable the Developer tab following the instructions provided
earlier.

• Open Excel:
• Launch Microsoft Excel.

• Go to Developer Tab:
• Click on the “Developer” tab in the Excel ribbon.

• Record Macro:
• In the Developer tab, click on “Record Macro.”

2021-2024 Pg. No.10


BRAINALYST - VBA SERIES

• Macro Dialog Box:


• In the “Record Macro” dialog box:
• Macro Name: Enter a name for your macro.
• Shortcut key (Optional): Assign a shortcut key (e.g., Ctrl + Shift + M).
• Store macro in: Choose “This Workbook” to make it available in the current workbook.
• Description (Optional): Add a description if needed.

• Select Location:
• Choose where to store the macro: “New Workbook” or “This Workbook.”

• Click OK:
• Click “OK” to start recording.

• Perform Actions:
• Excel is now recording your actions. Perform the actions you want to automate.

• Stop Recording:
• After completing the actions, go back to the Developer tab and click on “Stop Record-
ing.”

Saving macros workbook:


• Go to File > Save As > Browse
• Select the correct path to save the workbook
• Choose Excel Macro-Enabled Workbook (.xlsm)*
• Select Save

Pg. No.11 2021-2024


BRAINALYST - VBA SERIES

View the Generated VBA Code:

• Press Alt + F11 to open the Visual Basic for Applications (VBA) editor.

• In the Project Explorer window, you’ll see a new module (Module1 or similar) with the recorded
macro.
• Double-click on the module to view the generated VBA code.

2021-2024 Pg. No.12


BRAINALYST - VBA SERIES

Tips for Understanding Recorded VBA Code:


• Cell References:
• Recorded actions often include cell references. Understand which cells are being referred to
and modify them as needed.

• Object Methods:
• Actions like formatting or copying often involve object methods (e.g., Selection.Font.Bold =
True). Understand the object (e.g., Font) and the method (e.g., Bold).

• Relative References:
• Recorded macros may use relative references. For more dynamic code, consider converting
them to absolute references or using variables.

• Cleanup Code:
• The recorded code might include unnecessary or redundant lines. Review and clean up the
code for efficiency.

• Enhancements:
• Add additional VBA code to enhance or customize the recorded macro further.

Understanding the Simple Macro Code: 15 code

• Sub Macro1():
• Sub: Keyword indicating the start of a Sub procedure (macro).
• Macro1: The name of the macro. You can choose any valid identifier.
• (): Parentheses that may contain parameters (empty in this example).
• End Sub: Keyword indicating the end of the Sub procedure.

• Explanation:
• The code defines a macro named Macro1.
• Range(“B2”).FormulaR1C1 = “=RC[-1]*2”:
• Range(“B2”): Refers to cell B2 in the active sheet.
• .FormulaR1C1: Indicates that you are assigning a formula using the R1C1 reference
style.
• =: Starts the formula assignment.
• ‘=RC[-1]*2’: The formula to be assigned, multiplying the value in the cell one column
to the left by 2 using R1C1 notation.

• Explanation:
• The code sets the formula of cell B2 to be equal to two times the value in the cell one
column to the left.

• Formula Reference Styles:


• A1 Style:
• A1 reference style uses letters for columns and numbers for rows (e.g., A1, B2).

Pg. No.13 2021-2024


BRAINALYST - VBA SERIES

• R1C1 Style:
• R1C1 reference style uses numbers for both rows and columns and represents the
relative distance from the current cell (e.g., R1C1, R[3]C[3], RC[-1]).
• Difference Between A1 and R1C1 Styles:

• A1 Style:
• Columns are represented by letters (A, B, C).
• Rows are represented by numbers (1, 2, 3).
• Example: A1, B2, C3.

• R1C1 Style:
• Rows are represented by numbers followed by columns.
• Positive numbers represent cells below and/or to the right.
• Negative numbers represent cells above and/or to the left.
• Example: R1C1 (same as A1), R[3]C[3] (3 rows down, 3 columns to the right), RC[-1]
(same row, 1 column to the left).

• End Sub:
• End Sub: Keyword indicating the end of the Sub procedure (macro).
• Where to Write VBA Code:

• Module:
• A module is an area where you write VBA code.
• To insert a module, go to Insert > Module.
• To view a module, double-click on its icon in the Project Explorer window in the VBA
Editor (ALT + F11).
• Putting It All Together:
• Open Excel and press ALT + F11 to open the Visual Basic for Applications (VBA) Editor.
• Insert a module (Insert > Module).
• Copy and paste the provided VBA code into the module.
• You can run the macro Macro1 from the Excel interface or assign it to a button for easy
execution.

List of hands-on examples to help you write your first macro.


• Write Value into a Cell:

• Explanation:
• This macro writes the value 12 into cell B3 of the active sheet using the Range property.

• Add the Same Value into Multiple Ranges:

2021-2024 Pg. No.14


BRAINALYST - VBA SERIES

• Explanation:
• This macro enters the value 12 into cells B3 through B5 and C5 through C8 using a sin-
gle statement by specifying multiple ranges.

• Select a Cell:

• Explanation:
• This macro selects cell B3 in the active sheet using the Select method.

• Select Multiple Ranges:

• This macro selects the ranges B3:B5 and C5:C8 in the active sheet using the Select method.

• Copy/Paste:

• Copy/Paste Cell Value Only (Not Formula):

• Explanation:
• This macro copies only the values (not formulas) from B3:B5 and pastes them into cells
starting from G3.

• Copy the Entire Data from One Sheet to Another Sheet:

Pg. No.15 2021-2024


BRAINALYST - VBA SERIES

• Explanation:
• This macro copies the entire data from “Sheet1” to “Sheet2” in the active workbook.

• Copy the Entire Row and Paste It to Another Row:

• Explanation:
• This macro copies the entire row (5th row) from “Sheet1” and pastes it to the 7th row in
the same sheet.

• Clear Contents Only:

• Explanation:
• This macro clears only the contents of cells in the range A2:B4.

• Clear All Formats and Values:

• Explanation:
• This macro clears all formats and values from cells in the range A2:B4.

• Select the Leftmost Non-Empty Cell in a Row:

• Explanation:
• This macro moves the cursor to the leftmost non-blank cell in the active row.

• Select the Rightmost Non-Empty Cell in a Row:

2021-2024 Pg. No.16


BRAINALYST - VBA SERIES

• Explanation:
• This macro moves the cursor to the rightmost non-blank cell in the active row.

• Select the Last Non-Empty Cell in a Column:

• Explanation:
• This macro moves the cursor to the last non-blank cell in the active column.

• Select the First Non-Empty Cell in a Column:

• Explanation:
• This macro moves the cursor to the first non-blank cell in the active column.

Control Structures:
Control structures in Excel VBA are essential elements that allow you to control the flow of your program.
They help you make decisions, repeat actions, and create more dynamic and flexible code.
• Use If...Then...Else for conditional statements.
• Use For...Next for loops.
• Use Do...Loop for indefinite loops.

1. If...Then...Else Conditional Statement:

• If...Then...Else allows the execution of different blocks of code based on specified conditions.
• condition and anotherCondition are expressions that result in a Boolean value (True or False).
• If condition is true, the code block after Then is executed. If not, it checks the ElseIf conditions,
and if none are true, it executes the code block after Else.

Pg. No.17 2021-2024


BRAINALYST - VBA SERIES

• When to Use:
• Decision-Making: Use when you need to make decisions in your code based on certain
conditions.

• Rules:
• Conditions must evaluate to Boolean values.
• Each If statement should be terminated with End If.
• ElseIf and Else sections are optional.

Hierarchy and dot Notation


• Hierarchy in VBA Excel:
• Hierarchy refers to the structure and organization of objects within Excel. In VBA, Excel follows
a hierarchical structure where objects are organized in a tree-like fashion. Understanding this
hierarchy is crucial for accessing and manipulating different elements in Excel.

• The basic hierarchy is as follows:


• Application: Represents the Excel application itself.
• Workbook: Represents an Excel workbook.
• Worksheet: Represents a worksheet within a workbook.
• Range: Represents a cell or a group of cells within a worksheet.

• Dot Notation:
• Dot notation is a way of referencing objects and their properties/methods within the
hierarchy. It uses a period (.) to navigate through the hierarchy and access specific
elements. Each dot connects an object to its child object or property.

• Workbook Object (myWorkbook): References the specific workbook named “My-


Workbook.xlsx.”
• Worksheet Object (myWorksheet): References the worksheet named “Sheet1” with-
in the workbook.
2021-2024 Pg. No.18
BRAINALYST - VBA SERIES

• Range Object (myRange): References the cell A1 within the worksheet.


• Changing Value: Using the Value property to change the content of cell A1.

• Benefits of Hierarchy and Dot Notation:


• Precise Access: Helps in precisely targeting specific elements in Excel.
• Structured Code: Makes the code more organized and readable.
• Modularity: Allows working with different parts of Excel independently.
• The If...Then...Else statement allows you to perform different actions based on a con-
dition.

• If condition Then:
• condition: A logical expression that evaluates to either True or False.
• If the condition is true, the code within the If block is executed.

• Code within the If Block:


• This is the block of code that is executed if the condition specified after the If key-
word is true.
• In the example, if the value of x is greater than 5, a message box saying “x is greater
than 5” will be displayed.

• Else:
• If the condition specified after the If keyword is false, the code within the Else block
is executed.

• Code within the Else Block:


• This is the block of code that is executed if the condition specified after the If key-
word is false.
• In the example, if the value of x is not greater than 5, a message box saying “x is not
greater than 5” will be displayed.

• End If:
• Marks the end of the If...Then...Else block.

Pg. No.19 2021-2024


BRAINALYST - VBA SERIES

2. For...Next Loop:
• The For...Next loop is used to iterate a specific number of times.
• The For...Next loop allows you to repeat a block of code for a specified number of times or
over a specified range of values. It is particularly useful when you know in advance how
many times you want the loop to run.

• The loop iterates from 1 to 5.


• In each iteration, a string is concatenated with the current iteration number.
• After the loop, a message box displays the results.
• counter_variable: A variable used to control the loop. It keeps track of the current iteration.
• start_value: The initial value of the counter variable.
• end_value: The final value of the counter variable. The loop stops when the counter variable
reaches or exceeds this value.
• [Step step_value] (optional): Specifies the increment between each iteration. If omitted, the
default is 1.
• Next [counter_variable]: Indicates the end of the loop. If the counter_variable is specified
after Next, it is optional.

2021-2024 Pg. No.20


BRAINALYST - VBA SERIES

• Initialization (For i = 1 To 5):


• i is the counter variable initialized to 1 (start_value).
• The loop will run as long as i is less than or equal to 5 (end_value).

• Loop Body (MsgBox “Iteration: “ & i):


• The code inside the loop (between For and Next) is executed.
• In this example, a message box displays the current iteration number.

• Increment (Next i):


• After executing the loop body, the Next i statement increments i by 1 (Step is implic-
itly 1).
• The loop goes back to the beginning, re-evaluates the condition, and repeats the pro-
cess until i exceeds 5.

• Termination:
• The loop terminates when i becomes greater than 5.

• Additional Notes:
• Step Value:
• You can specify a Step value to control the increment between iterations. For
example, For i = 1 To 10 Step 2 will increment i by 2 in each iteration.

• Looping Backward:
• You can use a negative Step value to loop backward. For example, For i = 10 To 1 Step
-1 will decrement i by 1 in each iteration.

Pg. No.21 2021-2024


BRAINALYST - VBA SERIES

3. Do...Loop Until Loop:

• The Do...Loop Until loop is used for indefinite loops based on a condition at the end of the
loop.
• The Do...Loop Until loop is another control structure in Excel VBA that allows you to repeat-
edly execute a block of code until a specified condition is true. This loop is useful when you
want to ensure that the code block runs at least once.

• Parameters:
• condition: A logical expression that, when evaluated to True, causes the loop to terminate.

• Initialization (i = 1):
• i is a counter variable initialized to 1.
• The loop will run at least once.
• Loop Body (MsgBox “Iteration: “ & i):
• The code inside the loop (between Do and Loop Until) is executed.
• In this example, a message box displays the current iteration number.

• Increment (i = i + 1):
• After executing the loop body, i is incremented by 1.

• Termination (Loop Until i > 5):


• The Loop Until statement checks the condition (i > 5).
• If the condition is True, the loop terminates; otherwise, it repeats the process.

• Additional Notes:
• Entry Condition:
• Unlike the Do While loop, the Do Until loop ensures that the code inside the loop

2021-2024 Pg. No.22


BRAINALYST - VBA SERIES
runs at least once, as the condition is evaluated at the end of the loop.

• Exiting a Loop Prematurely:


• You can use the Exit Do statement to exit the loop prematurely based on a certain
condition.

Pg. No.23 2021-2024


BRAINALYST - VBA SERIES

Hierarchy –object of sheet


• Application
• Workbooks
• Workbooks sheets
• -range
• -cells
• -rows
• -column
• -charts
• -pivot tables
• -shaps
Excel VBA, the hierarchy of objects related to a worksheet can be visualized as a tree-like structure. At the
top level, you have the Application object, which represents the Excel application itself. Below the Applica-
tion object, you have the Workbook object, which represents an Excel workbook. Within a workbook, you
have the Worksheets collection, and each worksheet is represented by a Worksheet object.
• Simplified representation of the hierarchy:
• Application Object (Top Level)
• Workbook Object
• Worksheets Collection
• Worksheet Object

VBA, you can copy data from multiple sheets and paste it into a new sheet one
by one using a loop.

• It sets the source workbook (the workbook containing the sheets you want to copy) and creates a
new workbook.
• It loops through each sheet in the source workbook.
• For each sheet, it copies the used range of data.

2021-2024 Pg. No.24


BRAINALYST - VBA SERIES

• It determines the last row in the new sheet and pastes the data starting from the next row.
• It clears the clipboard to avoid any issues.
• After looping through all sheets, it optionally autofits columns in the new sheet.

• You can customize this code based on your specific requirements, such as adjusting the destination
range, formatting options, and more.
Practice:
How to clear content from worksheet:
• VBA code to clear the contents of all cells in the active sheet of the active workbook

Pg. No.25 2021-2024


BRAINALYST - VBA SERIES

• Sub ClearContentsOfActiveSheet():
• Sub: Indicates the beginning of a subroutine (macro).
• ClearContentsOfActiveSheet: Name of the subroutine.

• Clear contents of all cells in the active sheet:


• Single apostrophe indicates a comment. Comments are not executed and are used for providing
explanations.

• ActiveSheet.Cells.ClearContents:
• ActiveSheet: Refers to the currently active sheet in the active workbook.
• Cells: Refers to all cells in the active sheet.
• ClearContents: Method to clear the contents of the selected cells.

• Execution Steps:
• When you run this macro, it clears the contents of all cells in the active sheet.
• The ActiveSheet property dynamically refers to the sheet that is currently active when the code
runs.
• The ClearContents method removes the values and formulas from the cells while keeping the
formatting intact.
Getting 3 workbook data in one sheet

VBA code that appends data from different workbooks when the source work-
book names are known.

2021-2024 Pg. No.26


BRAINALYST - VBA SERIES

• Sub AppendDataFromWorkbooks():
• Sub: Indicates the beginning of a subroutine (macro).
• AppendDataFromWorkbooks: Name of the subroutine.

• ‘ Declare variables:
• Single apostrophe indicates a comment. Comments are not executed and are used for providing
explanations.

• Set mainWorkbook = ThisWorkbook:


• ThisWorkbook: Refers to the workbook where the code is written. Change it if the code is in a
different workbook.

• Set targetSheet = mainWorkbook.Sheets(1):


• Sets the target sheet in the main workbook where the data will be appended. Assumes data will
be appended to the first sheet.

Pg. No.27 2021-2024


BRAINALYST - VBA SERIES

• Array of source workbook names:


• SourceWorkbookNames: Array containing names of source workbooks.

• Loop through each source workbook name:


• For Each sourceWorkbookName In sourceWorkbookNames:
• Loop iterates through each source workbook name.

• Open the source workbook:


• Set sourceWorkbook = Workbooks.Open(sourceWorkbookName):

• Opens the source workbook.


• Set the source sheet (assuming data is in the first sheet):
• Set sourceSheet = sourceWorkbook.Sheets(1):
• Sets the source sheet in the source workbook. Assumes data is in the first sheet.

• Copy data from the source sheet to the target sheet:


• sourceSheet.UsedRange.Copy targetSheet.Cells(targetSheet.Rows.Count, 1).End(xlUp).Off-
set(1):
• Copies data from the source sheet to the target sheet. The data is pasted below the last used row
in the target sheet.

• Close the source workbook without saving changes:


• SourceWorkbook.Close False:
• Closes the source workbook without saving changes.

• Inform the user that data appending is complete:


• MsgBox “Data appending is complete!”, vbInformation:
• Displays a message box informing the user that data appending is complete.

• Execution Steps:
• When you run this macro, it appends data from the specified source workbooks to the target
sheet in the main workbook.
• The source workbook names are specified in the sourceWorkbookNames array.
• The ThisWorkbook property refers to the workbook where the code is written. If the code is in
a different workbook, adjust it accordingly.
• The appended data is pasted below the last used row in the target sheet.

Append data from different workbooks when source workbook names are un-
known
• VBA code to append data from different workbooks when the source workbook names are unknown.
The code dynamically selects all Excel files in a specified folder and appends their data to a target
sheet in the main workbook.

2021-2024 Pg. No.28


BRAINALYST - VBA SERIES

• Sub AppendDataFromUnknownWorkbooks():
• Sub: Indicates the beginning of a subroutine (macro).
• AppendDataFromUnknownWorkbooks: Name of the subroutine.
• ‘ Declare variables:
• Single apostrophe indicates a comment. Comments are not executed and are used for providing
explanations.
• Set mainWorkbook = ThisWorkbook:
• ThisWorkbook: Refers to the workbook where the code is written. Change it if the code is in a dif-
ferent workbook.
• Set targetSheet = mainWorkbook.Sheets(1):
• Sets the target sheet in the main workbook where the data will be appended. Assumes data will be

Pg. No.29 2021-2024


BRAINALYST - VBA SERIES

appended to the first sheet.


• Set folderPath = “C:\Path\To\Your\Folder”:
• Sets the folder path where the source workbooks are located. Change it to the actual folder path.

• Get the first file in the folder:


• FileName = Dir(folderPath & “*.xlsx”):
• Uses the Dir function to get the first file in the folder with the specified extension.

• Loop through each file in the folder:


• Do While fileName <> “”:
• Initiates a loop that continues until there are no more files in the folder.

• Open the source workbook:


• Set sourceWorkbook = Workbooks.Open(folderPath & fileName):
• Opens the source workbook.
• Set the source sheet (assuming data is in the first sheet):
• Set sourceSheet = sourceWorkbook.Sheets(1):
• Sets the source sheet in the source workbook. Assumes data is in the first sheet.
• Copy data from the source sheet to the target sheet:
• SourceSheet.UsedRange.Copy targetSheet.Cells(targetSheet.Rows.Count, 1).End(xlUp).
Offset(1):
• Copies data from the source sheet to the target sheet. The data is pasted below the last used
row in the target sheet.
• Close the source workbook without saving changes:
• SourceWorkbook.Close False:
• Closes the source workbook without saving changes.

• Get the next file in the folder:


• FileName = Dir:
• Gets the next file in the folder.

• Inform the user that data appending is complete:


• MsgBox “Data appending is complete!”, vbInformation:
• Displays a message box informing the user that data appending is complete.

Procedures and Functions in VBA:


• What are Procedures?
• Definition: In VBA (Visual Basic for Applications), a procedure is a set of instructions that per-
form a specific task.

• Types:

• Subroutine (Sub): A subroutine is a procedure that doesn’t return a value.


• Function: A function is a procedure that returns a value.
• What are Functions?
• Definition: Functions are procedures that return a value after performing a specific
task.
• Declaration: Functions are declared using the Function keyword.
• Return Type: Functions specify the type of value they return using the As keyword.

• Example Function:

2021-2024 Pg. No.30


BRAINALYST - VBA SERIES

• In this example, AddNumbers is a function that takes two parameters (x and y) and
returns their sum.

3. When to Use Procedures:


• Subroutines (Subs):
• Use subs when you want to perform a specific task without returning a value.
• Subs are handy for tasks like formatting data, copying values, displaying messag-
es, etc.

4. When to Use Functions:


• Functions:
• Use functions when you want to perform a task and return a value.
• Functions are suitable for calculations, validations, and operations where a result
is needed.

5. Key Differences:
• Return Value:
• Subs don’t return a value (Sub MySubroutine()).
• Functions return a value (Function MyFunction() As Integer).

• Usage in Expressions:
• Subs are typically called for their side effects.
• Functions are used in expressions or assigned to variables.

6. Parameter Passing:
• Subroutines and Functions can accept parameters:
• Parameters allow passing information to the procedure.
• Parameters are enclosed in parentheses after the procedure name.

7. Scope of Variables:
• Local vs. Global:
• Variables declared inside a procedure are local to that procedure.
Pg. No.31 2021-2024
BRAINALYST - VBA SERIES

• Variables declared outside any procedure are global and can be used by any pro-
cedure in the module.

8. Error Handling:
• On Error Statement:
• Use On Error Resume Next to continue with the next line of code on error.
• Use On Error GoTo 0 to turn off error handling.

• Exiting Procedures Prematurely:


• Exit Statement:
• Exit Sub is used to exit a subroutine.
• Exit Function is used to exit a function.

Creating user from using VBA


• Create an Excel VBA Userform. The Userform we are going to create looks as follows:
• VBA (Visual Basic for Applications) is a customizable dialog box that you can create in Excel to in-
teract with users. UserForms provide a way to collect input, display information, or perform specific
actions using a graphical interface within Excel.

• Open Excel and Access the Developer Tab:


• If the Developer tab is not visible in the Excel ribbon, you need to enable it.
• Go to “File” -> “Options” -> “Customize Ribbon.”
• Check the “Developer” option, and click “OK.”

• Access the VBA Editor:


• Click on the “Developer” tab.
• Click on “Visual Basic” to open the VBA editor.

• Insert a UserForm:
• In the VBA editor, right-click on any object in the “Project Explorer” (usually on the left
side).
• Choose “Insert” -> “UserForm.”

• Design the UserForm:


• The UserForm will appear as a blank dialog box.
• You can add various controls (such as TextBoxes, Labels, Buttons, etc.) from the “Toolbox”
to the UserForm.
• To access the “Toolbox,” go to “View” -> “Toolbox” in the VBA editor.

2021-2024 Pg. No.32


BRAINALYST - VBA SERIES

• Add Controls to the UserForm:


• Drag and drop controls from the Toolbox onto the UserForm.
• For example, you can add a TextBox for user input, Labels to display text, Buttons for ac-
tions, etc.

• Set Properties:
• Select each control, and set its properties using the “Properties” window.
• You can change properties such as names, captions, default values, etc.

• Write VBA Code for UserForm Actions:


• To make the UserForm functional, you need to write VBA code.
• Double-click on the controls to access their event procedures, such as “Click” for buttons
or “Change” for textboxes.
• Write VBA code to define what should happen when a user interacts with the controls.

• Run the UserForm:


• Close the VBA editor.
• Go back to Excel, and you can run the UserForm by clicking a button, using a macro, or any
other triggering event.

Userform

• Create own user form using VBA

• Add the Controls


• To add the controls to the Userform, execute the following steps.
1. Open the Visual Basic Editor. If the Project Explorer is not visible, click View, Project
Explorer.
2. Click Insert, Userform. If the Toolbox does not appear automatically, click View, Tool-
box. Your screen should be set up as below.

Pg. No.33 2021-2024


BRAINALYST - VBA SERIES

• Add the controls listed in the table below. Once this is done, ensure the outcome aligns with the Us-
erForm image displayed earlier. For instance, create a text box control by selecting TextBox from the
Toolbox and then dragging it onto the UserForm. When you reach the Car frame, be sure to create
this frame first before positioning the two option buttons within it.

• Controls (TextBox, ComboBox, CheckBox):


• i. TextBox:
• Definition: A TextBox is an input field where the user can enter text.

2021-2024 Pg. No.34


BRAINALYST - VBA SERIES

• ComboBox:
• Definition: A ComboBox is a drop-down list from which the user can select an option.

• CheckBox:
• Definition: A CheckBox is a box that the user can check or uncheck.

• Modify the names and captions of the controls as per the table below. Names are uti-
lized in the Excel VBA code, and captions are what appear on the screen. It is advisable
to customize control names to enhance code readability. To make these adjustments,
navigate to View, Properties Window, and click on each control.

• Show the Userform

• To show the Userform, place a command button on your worksheet and add the fol-
lowing code line:

Pg. No.35 2021-2024


BRAINALYST - VBA SERIES

• We are now going to create the Sub UserForm_Initialize. When you use the Show meth-
od for the Userform, this sub will automatically be executed.

1. Open the Visual Basic Editor.


2. In the Project Explorer, right click on DinnerPlannerUserForm and then click View
Code.
3. Choose Userform from the left drop-down list. Choose Initialize from the right
drop-down list.
4. Add the following code lines:

2021-2024 Pg. No.36


BRAINALYST - VBA SERIES

Pg. No.37 2021-2024


BRAINALYST - VBA SERIES

• Test the Userform


• Exit the Visual Basic Editor, enter the labels shown below into row 1 and test the Userform.
• Event Handling for UserForms:
• Definition: Events are actions or occurrences that happen within a UserForm, such as a button
click, a change in a TextBox, etc.

• Common Events:
• Click Event: Occurs when a control is clicked.
• Change Event: Occurs when the content of a control changes.
• Activate/Deactivate Events: Occur when the UserForm is activated or deactivated.

• Handling Events:
• Double-click on a control in the UserForm to open the code window for its default event (e.g.,
CommandButton_Click for a button).
• Manually select a control and an event from the drop-down menus at the top of the code window.

• Additional Notes:
• Positioning and Sizing Controls:
• Use the Properties window to set properties like Top, Left, Width, and Height for precise
control positioning and sizing.

• Adding Controls Dynamically:


• You can add controls dynamically using VBA code. For example, adding items to a ListBox dy-
namically.

• Event Procedures:
• Event procedures are the code that runs in response to a specific event.
• Event procedures are written in the code window associated with the UserForm.

• Advanced Controls:
• User Forms support various advanced controls such as ListBox, SpinButton, OptionButton, and
more.

• Data Validation:
• Use User Forms to collect and validate user input before processing it in your Excel workbook.

Arrays:
• What are arrays –same data type of collection.
• Understanding Arrays:
• Definition:

2021-2024 Pg. No.38


BRAINALYST - VBA SERIES

• An array in VBA is a collection of variables of the same data type under a single name.
• Arrays are used to store and manipulate multiple values efficiently.

• Key Concepts:
• Declaration:
• Declare an array using the Dim keyword, specifying the array’s name and size (optional for
dynamic arrays).

• The size represents the number of elements in the array. In the example above, myArray has
four elements with indexes 0 to 3.
• An array is a data structure that allows you to store a collection of elements, all of the same
data type, under a single variable name. Each element in the array is identified by an index
or a key. The key could be a number (for example, in the case of arrays in programming lan-
guages like C or VBA), or it could be a more complex structure (as in the case of associative
arrays in some programming languages).
• In the context of programming and VBA in Excel, an array is particularly useful when you
want to group related pieces of data together. Instead of having individual variables for each
piece of data, you can use an array to store them collectively. This makes it easier to manage
and manipulate large sets of data.

• Here are some key characteristics of arrays:


• Homogeneous Data Type: All elements in an array must be of the same data type. For exam-
ple, if you declare an array of integers, all elements in that array must be integers.

• Indexing:
• Arrays in VBA are zero-based, meaning the first element has an index of 0.
• Access elements using their index.

• In this example, the value 10 is assigned to the first element of myArray.

• Dynamic Arrays:
• Declare dynamic arrays using the Dim statement without specifying a size.
• Use the ReDim statement to resize a dynamic array.

• Multi-dimensional Arrays:
• Multi-dimensional arrays have multiple indices, forming a grid-like structure. Useful for
representing tables or matrices.
• Dive into multi-dimensional arrays in VBA Excel in more depth. Multi-dimensional arrays
are arrays with more than one dimension, allowing you to organize data in a table-like struc-
ture with rows and columns. Here, we’ll cover the declaration, initialization, accessing ele-
ments, dynamic resizing.

• Declaration and Initialization:


• Accessing Elements:
• Dynamic Resizing:
• You can dynamically resize multi-dimensional arrays using the ReDim statement.

Pg. No.39 2021-2024


BRAINALYST - VBA SERIES

• Iterating through a Multi-dimensional Array:

• Jagged Arrays:

• Arrays are often used with loops for efficient data processing. The For Each loop is beneficial
for iterating through each element.
Application of Array
• Arrays are widely used in VBA Excel for various purposes, enhancing the efficiency and flexibility of
your code.

• Data Storage:

• Application:
• Storing a list of employee names or other data sets in a structured manner.

• Data Processing:

• Application:
• Iterating through an array to perform calculations, validations, or other data process-
ing tasks.

• Matrix Operations:

• Application:
• Performing matrix operations such as multiplication, addition, and manipulation for
mathematical or engineering applications.

2021-2024 Pg. No.40


BRAINALYST - VBA SERIES

• Storing and Retrieving Data from Worksheets:

• Application:
• Storing data from a range in a worksheet into an array for efficient manipulation and
analysis.
Basic Algorithm of Sorting

• Sorting is a fundamental algorithmic operation used in computer science to rearrange elements in


a specific order. There are various sorting algorithms, each with its own characteristics, advantages,
and disadvantages.

• Algorithm:
• Start from the beginning of the array.
• Compare each pair of adjacent elements.
• If the elements are in the wrong order, swap them.
• Continue this process until the entire array is sorted.
• Repeat the process for each element until no more swaps are needed.

• Array Sorting and Searching:


• Sorting and searching algorithms can be applied to arrays for data analysis. Excel VBA
provides functions like Sort() and Filter().

Pg. No.41 2021-2024


BRAINALYST - VBA SERIES

Working with databases in Excel VBA:


Working with Databases:
• Connecting to Databases:
• Connecting to databases in Excel VBA involves establishing a link between your Excel workbook
and a database. The commonly used method is through ActiveX Data Objects (ADO). ADO allows
you to connect to various databases like SQL Server, Access, Oracle, etc.

• Connection String: A connection string contains the information needed to connect to the data-
base, including the server’s location, authentication details, and database name.

• ADO Objects: ADO relies on objects such as Connection and Recordset. The Connection object man-
ages the connection settings, while the Recordset object holds the data retrieved from the database.

• b. Executing SQL Queries:


• Once connected to a database, you can execute SQL queries to interact with the data. This
involves sending SQL commands to the database and retrieving the results.

• SQL Commands: Structured Query Language (SQL) commands like SELECT, INSERT, UPDATE,
DELETE are used to manipulate the data in the database.

• Parameters: You can use parameters in your SQL queries to make them dynamic and handle
user inputs or variables within your VBA code.

2021-2024 Pg. No.42


BRAINALYST - VBA SERIES

• c. Retrieving and Manipulating Data:


• After executing a query, you retrieve the data using the Recordset object. You can then
manipulate this data within your Excel workbook.

• Recordset Methods: Methods like MoveFirst, MoveNext, MoveLast, and MovePrevious are
used to navigate through the records.

• Excel Integration: You can transfer the data from the Recordset object to Excel ranges, allow-
ing for further analysis or visualization.

User-Defined Function (UDF) in VBA (Visual Basic for Applications) allows you to cre-
ate custom functions that can be used in Excel, similar to built-in functions like SUM
or VLOOKUP.
• Step 1: Open the VBA Editor
• Press ALT + F11 to open the VBA editor in Excel.

• Step 2: Insert a New Module


• In the VBA editor, right-click on any item in the Project Explorer (usually on the left side) and
choose Insert -> Module. This creates a new module where you can write your VBA code.

• Step 3: Write Your User-Defined Function


• In the module, write your UDF. A basic example might be a function that adds two numbers:

• Function: Keyword to define a function.


• AddNumbers: Name of the function.
• number1 and number2: Parameters that the function takes.
• As Double: Specifies the data type the function returns (in this case, a double).
• AddNumbers = number1 + number2: Actual code that performs the addition.

• Step 4: Use the UDF in Excel


• Close the VBA editor (ALT + Q) and go back to Excel.
• You can now use your UDF in a cell like any other Excel function. For example, if you put =Add-
Numbers(A1, B1) in a cell, it will add the values from cells A1 and B1.

• Explanation of Key Concepts:


• Function Keyword: Begins the definition of the function.
• Function Name: This is the name you give to your function. It should be unique within
the workbook.

Pg. No.43 2021-2024


BRAINALYST - VBA SERIES

• Parameters: These are the values that the function receives as input. In the example, number1 and
number2 are parameters.

• Return Type: The As Double part specifies the data type of the value that the function will return.
You can use other data types like String, Integer, etc., depending on the nature of your function.

• Function Body: This is where you write the actual code for your function. In the example, AddNum-
bers = number1 + number2 assigns the sum of number1 and number2 to the function’s name.

• Important Notes:
• Ensure your function names are unique to avoid conflicts with built-in Excel functions.
• Always include error handling and validation as needed.
• Parameters must be enclosed in parentheses.
• You can have multiple parameters or none at all, depending on your function’s require-
ments.

• User-Defined Functions (UDFs) in VBA by exploring different examples.


• Basic Arithmetic Operations

2021-2024 Pg. No.44


BRAINALYST - VBA SERIES

• Function Declaration:
• Function: This keyword is used to declare a function.
• AddNumbers and MultiplyNumbers: These are the names of the functions. You can choose
meaningful names for your functions.

• Parameters:
• (number1 As Double, number2 As Double): These are the input parameters of the functions.
The As Double part specifies that these parameters should be of the Double data type (numeric
values with decimal points).

• Return Type:
• As Double: Specifies the data type of the value that the function will return. In both cases, the
functions return a Double value, which is the result of the arithmetic operation.

• Function Body:
• AddNumbers = number1 + number2: This line performs the addition operation. The result of
the addition (number1 + number2) is assigned to the function name (AddNumbers), effectively
making this the return value of the function.

• MultiplyNumbers = number1 * number2: Similarly, this line performs the multiplication oper-
ation. The result of the multiplication (number1 * number2) is assigned to the function name
(MultiplyNumbers), making it the return value of the function.

• Example Usage:
• Once you have defined these functions in your VBA module, you can use them in Excel formulas.
For example, if you have values in cells A1 and B1, you can use the functions in a cell like this:
• =AddNumbers(A1, B1): This will add the values in cells A1 and B1.
• =MultiplyNumbers(A1, B1): This will multiply the values in cells A1 and B1.

VBA (Visual Basic for Applications), parameters are passed by reference by default.
This means that when you pass a variable to a procedure or function, you are actually
passing a reference to the memory location where the variable is stored. As a result,
changes made to the parameter within the procedure or function affect the original
variable outside the procedure or function.

Pg. No.45 2021-2024


BRAINALYST - VBA SERIES

• Example Procedure initializes a variable myNumber with the value 10.


• It then calls the ModifyNumberByReference procedure and passes myNumber by reference using
the ByRef keyword.
• Inside the ModifyNumberByReference procedure, the value of the parameter num is modified (dou-
bled).
• After returning from the procedure, the modified value of myNumber is displayed using a MsgBox.
• When you run this code, the message box will display “Modified Value: 20” because the original vari-
able myNumber was modified within the ModifyNumberByReference procedure.
• It’s important to note that using ByRef is the default behavior, and you don’t necessarily have to ex-
plicitly specify it. However, doing so can improve code readability and make it clear that changes to
the parameter affect the original variable. If you want to explicitly pass by value (creating a copy of
the variable), you can use the ByVal keyword.

VBA (Visual Basic for Applications), you can call a subroutine using its name followed
by parentheses.

• MySubroutine is a subroutine that contains some code (in this case, a MsgBox displaying a message).
• CallMySubroutine is another subroutine that calls MySubroutine. The call is made by simply writing
the name of the subroutine followed by parentheses.
• When you run the CallMySubroutine subroutine, it will execute the code within MySubroutine.
VBA (Visual Basic for Applications), you can use events to respond to actions or
changes in a workbook. Events are triggered automatically when certain actions oc-
cur, and you can write VBA code to handle those events.
• Workbook Events:
• Workbook events are triggered by actions related to the workbook, such as opening or closing

2021-2024 Pg. No.46


BRAINALYST - VBA SERIES

the workbook, changing a sheet, saving, etc. To work with workbook events, you need to open
the VBA editor by pressing ALT + F11. In the editor, you will find a list of objects in the left pane,
including the ThisWorkbook object. Double-clicking on ThisWorkbook opens a code window
where you can write event-handling code.

• Here are some common workbook events:


• Open Event:
• Triggered when the workbook is opened.
VBA (Visual Basic for Applications) for Excel, there are two main types of loops: the
For...Next loop and the For Each...Next loop.
1. For...Next Loop:
• The For...Next loop is used when you know the number of times you want to repeat a block of
code. It follows the syntax:

• Counter_variable: A variable that will keep track of the iteration.


• Start_value: The initial value of the counter_variable.
• End_value: The final value of the counter_variable (when the loop should stop).
• Step step_value: Optional; defines the increment (or decrement) between each iteration. If
omitted, the default is 1.

2. For Each...Next Loop:

• The For Each...Next loop is used when you want to iterate over elements in a collection, like an
array, a range of cells, or a collection of objects.

• Element: A variable that represents the current element in the collection.


• Collection: The collection of elements to iterate over.

Pg. No.47 2021-2024


BRAINALYST - VBA SERIES

Error handling in VBA (Visual Basic for Applications) in Excel is crucial for managing
unexpected errors that may occur during the execution of your code. It helps prevent
abrupt termination of the program and allows you to handle errors in a controlled
and informative way.
1. On Error Statement:
• The On Error statement is used to enable or disable error handling within a procedure. It has
three main forms:

• On Error Resume Next:


• This statement tells VBA to continue executing the code even if an error occurs. It ef-
fectively ignores the error and continues with the next line of code.

2021-2024 Pg. No.48


BRAINALYST - VBA SERIES

• On Error GoTo [label]:


• This statement directs the execution to a specified label if an error occurs. You need to
have a corresponding GoTo statement with the specified label to handle the error.

• On Error GoTo 0:
• This statement disables error handling and returns the program to its default behav-
ior, where it stops execution when an error occurs.

2. Err Object:

• The Err object provides information about the most recent runtime error. It has properties such
as Number (error code), Description (error description), and Source (name of the object/mod-
ule where the error occurred).

3. Specific Error Handling:

• You can use On Error GoTo with specific error codes to handle different types of errors differ-
ently.

• Explanation:
• On Error GoTo ErrorHandler:
• This line tells VBA that if an error occurs during the execution of the code within the
current procedure, it should jump to the specified label named ErrorHandler to handle
the error.

Pg. No.49 2021-2024


BRAINALYST - VBA SERIES

• ‘Code that might cause an error:


• This comment represents the section of code where an error might occur. It could be
any operation or calculation that has the potential to cause a runtime error.

• Exit Sub:
• This line is reached if no error occurs during the execution of the preceding code.
It’s an explicit exit statement that tells the program to exit the current subroutine or
function.

• Error Handler:
• This is a label indicating the starting point of the error-handling routine. When an
error occurs, the program jumps to this label.
• If Err.Number = 6 Then:
• This line checks if the error number stored in the Err object is equal to 6. Error num-
ber 6 typically indicates a “Division by zero” error.
• MsgBox “Division by zero error!”:
• If the error number is 6, it means a division by zero error occurred. In this case, a mes-
sage box is displayed informing the user about the specific error.
• Else:
• If the error number is not 6 (meaning a different type of error occurred), the program
executes the code following the Else statement.

• MsgBox “An unexpected error occurred!”:


• In case of any error other than a division by zero, this line displays a message box in-
forming the user that an unexpected error occurred.

• On Error GoTo ErrorHandler


• ‘Code that might cause an error
• Exit Sub ‘ If no error occurs, this line will be executed
• ErrorHandler:
• If Err.Number = 6 Then
• MsgBox “Division by zero error!”
• Else
• MsgBox “An unexpected error occurred!”
• End If

4. Resume Statement:
• The Resume statement is used to resume execution after an error occurs. It can be used with
different options, such as Next, Label, or 0.

• On Error Resume Next:


• This line instructs VBA to continue executing the code even if an error occurs. When an
error occurs, it is recorded in the Err object, but the program does not halt or display
an error message.

2021-2024 Pg. No.50


BRAINALYST - VBA SERIES

• ‘ Code that might cause an error:


• This comment represents the section of code where an error might occur. It could be
any operation or calculation that has the potential to cause a runtime error.

• If Err.Number <> 0 Then:


• This conditional statement checks if an error occurred by examining the Err.Number
property. If Err.Number is not equal to 0, it means an error occurred during the exe-
cution of the preceding code.

• ‘ Code to handle the error:


• If an error is detected, this block of code is executed to handle the error. It can include
actions such as logging the error, displaying a message to the user, or taking corrective
measures.
• Err.Clear:
• This line is used to clear the current error information stored in the Err object. By
clearing the error, you are signaling that you have handled the error, and the program
can continue executing the subsequent code without the presence of the previous
error.
• End If:
• This marks the end of the conditional statement. If an error was detected and han-
dled, the program proceeds to the next line; otherwise, it continues executing the sub-
sequent code.

• On Error GoTo 0:
• This line resets the error-handling behavior to the default mode. After this line, if an
error occurs, VBA will halt execution and display the default error message, unless
another On Error statement is encountered.

5. Error Propagation:
• You can allow errors to propagate up the call stack by not handling them in a specific procedure.
The error will then be caught by a higher-level error handler.

6. Logging and Notification:


• Consider logging or notifying users about errors to facilitate debugging and provide a better
user experience.

• Error handling in VBA involves using On Error statements, the Err object, and the Resume state-
ment to gracefully manage errors and provide meaningful information for debugging and user
interaction.

Pg. No.51 2021-2024


BRAINALYST - VBA SERIES

Charts:
• Excel VBA, you can create and manipulate charts using various objects and meth-
ods. Below is an in-depth explanation of working with charts in Excel VBA:

How can create chart using VBA


• VBA (Visual Basic for Applications) in Excel involves manipulating the ChartObjects and Chart ob-
jects. Below, I’ll provide an in-depth example that demonstrates how to create a simple bar chart
using VBA. This example assumes you have a worksheet with some data, and you want to create a
bar chart based on that data.

• Step-by-Step Guide to Creating a Bar Chart:

• Open Excel and Press Alt + F11 to Open the VBA Editor:
• You will be working in the VBA editor to write and run your VBA code.

• Insert a New Module:


• In the VBA editor, right-click on any item in the Project Explorer, choose Insert, and
then Module. This is where you will write your VBA code.

• Write VBA Code to Create a Bar Chart:


• Write the following VBA code in the module:

• Understanding Chart Objects:


• In Excel VBA, charts are represented by the ChartObject object.
• The Charts collection contains all chart sheets in a workbook.

• Creating a Chart:
• Use the Add method of the Charts collection to create a new chart.
• Specify the chart type and style during the creation.

2021-2024 Pg. No.52


BRAINALYST - VBA SERIES

• Modifying Chart Properties:


• Customize various chart properties such as title, axis labels, legend, etc.

• Chart Types:
• Change the chart type dynamically.

• Adding Series:
• Add and manipulate series within the chart.

• Formatting:
• Apply formatting to various elements of the chart.

• Deleting a Chart:
• Remove a chart using the Delete method.

Pivot in VBA –Excel


• What is a PivotTable?
• A PivotTable is a powerful tool in Excel that allows you to summarize and analyze large datasets
by rearranging and grouping data dynamically. It provides a flexible way to extract meaningful
insights and patterns.

• 2. Creating a PivotTable:
• Select any cell within your dataset.
• Go to the “Insert” tab and click on “PivotTable.”
• Select the range of data and choose where you want to place the PivotTable (new worksheet or
existing worksheet).
Pg. No.53 2021-2024
BRAINALYST - VBA SERIES

• Click “OK.”

• 3. PivotTable Fields:
• Values: The data you want to analyze (e.g., Sum of Sales).
• Rows: The categorical data that defines the rows (e.g., Product, Region).
• Columns: Additional categorization for columns.
• Filters: Filters data based on specific criteria.

• 4. PivotTable Layout:
• Rows and Columns Area: Drag fields to these areas to define the structure of your PivotTable.
• Values Area: Define how the data should be summarized (Sum, Count, Average, etc.).

• 5. Grouping and Sorting:


• Grouping: Combine data into groups for better analysis (e.g., group dates by months).
• Sorting: Arrange data in ascending or descending order.

• 6. Filtering:
• Report Filter: Filters the entire Pivot Table based on selected criteria.
• Slicer: Visual filter for easy data filtering.

• 7. Calculated Fields and Items:


• Calculated Fields: Create custom calculations based on existing fields.
• Calculated Items: Apply calculations to specific items within a field.

How can create pivot using VBA


• Pivot table using VBA (Visual Basic for Applications) in Excel involves using the PivotTable object
and related properties and methods. Below is an example that demonstrates how to create a pivot
table from a dataset in Excel using VBA.

• Creating a PivotTable:
• Use the Pivot Table Wizard method to create a new Pivot Table.

• Modifying PivotTable Fields:


• Add fields to the PivotTable’s Rows, Columns, Values, or Filters areas.

2021-2024 Pg. No.54


BRAINALYST - VBA SERIES

• Filtering and Sorting:

• Creating a Pivot Chart:


• Use the Pivot Charts Add method to create a new Pivot Chart.

• Apply filters and sorting to Pivot Table fields.


• Assumes that you have a dataset in columns A to D in a sheet named “Sheet1” and creates
a new worksheet for the pivot table. Adjust the range and field names according to your
specific data structure.

• Steps Explained:
• Set the Source Data Range:
• Set the dataSheet variable to the worksheet containing your source data.
• Set the pivotRange variable to the range of data you want to use for the pivot table.

• Create a New Worksheet for the Pivot Table:


• Create a new worksheet (pivotSheet) where the pivot table will be placed.

• Set the Pivot Cache:


• Create a pivot cache (pivotCache) using the source data range.
• Add the Pivot Table:
• Add the pivot table to the pivot Sheet using the pivot cache. Specify the table destina-
tion and give the pivot table a name.

• Specify Pivot Fields:


• Specify the fields for the pivot table. In this example, “Category” is set as a row field,
“Month” as a column field, and “Amount” as a data field with the sum aggregation.

• Customize as Needed:
• Customize the code based on your specific data and requirements. You can add more
row fields, column fields, and data fields, and adjust the aggregation functions.

• Run the VBA Code:


• Close the VBA editor and go back to your Excel workbook.
• Press Alt + F8 to open the “Macro” dialog.
• Select “Create Pivot Table” and click “Run.”

Pg. No.55 2021-2024


BRAINALYST - VBA SERIES

Introduction to Add-ins:
• Definition: An Excel Add-in is a supplemental program that adds custom commands or features to
Microsoft Excel.

• Purpose: Enhance Excel’s functionality by providing specialized tools or automating specific


tasks.

2. Types of Add-ins:

• COM Add-ins: Traditional add-ins created using the Component Object Model (COM).
• VSTO Add-ins: Developed using Visual Studio Tools for Office, often more powerful and com-
plex.
• Excel Web Add-ins: Developed using web technologies and compatible with Excel Online.

3. Creating Excel Add-ins in VBA:

• Developer Tab: To create and manage Excel Add-ins, the Developer tab must be enabled.
• VBA Editor: Open the Visual Basic for Applications (VBA) editor to write and manage code for
the Add-in.

2021-2024 Pg. No.56


BRAINALYST - VBA SERIES

4. Excel Add-in Structure:

• Workbook Object: Add-ins are often structured as hidden workbooks with specific event pro-
cedures.
• Code Modules: Store VBA code for custom functions, procedures, and event handlers.

5. Custom Functions and Procedures:

• Automation: Add-ins often automate repetitive tasks or calculations.


• User-Defined Functions (UDFs): Extend Excel’s set of built-in functions with custom functions.

6. Event Handlers:

• Workbook Events: Respond to events such as opening, closing, or saving workbooks.


• Worksheet Events: Capture user actions within specific worksheets.

7. Ribbon Customization:

• XML Markup: Customize the Ribbon interface with XML to add custom tabs, groups, and but-
tons.
• Callbacks: Associate VBA procedures with Ribbon controls to define their behavior.

8. Security and Trust Center:

• Digital Signatures: Sign Add-ins to establish trust and prevent security warnings.
• Trust Center Settings: Users may need to adjust settings to enable Add-ins.

9. Deployment:

• Sharing: Share Add-ins with others by distributing the .xlam file or publishing to a shared net-
work location.
• Centralized Deployment: IT administrators can deploy Add-ins centrally.

10. Updating Add-ins:

• Version Control: Maintain version numbers to track changes.


• Update Mechanism: Provide instructions or mechanisms for users to update the Add-in.

11. Error Handling:

• Graceful Handling: Implement error-handling to gracefully manage unexpected situations.


• Logging: Optionally, log errors for troubleshooting.

12. Testing and Debugging:

• VBA Editor: Use the VBA editor’s debugging tools for testing.
• Test on Various Systems: Ensure compatibility with different Excel versions.

13. Documentation:

• User Guide: Provide documentation for users, explaining the features and usage.
• Code Comments: Include comments in the VBA code for clarity and maintainability.

Pg. No.57 2021-2024


BRAINALYST - VBA SERIES

14. Compliance with Best Practices:

• Efficiency: Optimize code for performance.


• Compatibility: Ensure compatibility with various Excel versions and platforms.

15. Security Considerations:

• Data Privacy: Adhere to data privacy regulations when developing Add-ins.


• Access Permissions: Request only necessary permissions.

• How to add add-ins


• In build library for add-ins
• VBA Excel, add-ins are additional features or functionalities that you can integrate
into Excel to extend its capabilities. Creating and managing add-ins typically in-
volves creating a VBA project, adding modules, and then using the VBA editor to
write and organize your code.

• Creating a Basic VBA Add-In:


• Open Excel:
• Open Microsoft Excel.

• Open the VBA Editor:


• Press Alt + F11 to open the Visual Basic for Applications (VBA) editor.

• Create a New Module:


• In the VBA editor, right-click on any item in the Project Explorer, choose Insert, and then
Module. This is where your add-in code will reside.

• Write Your Add-In Code:


• Write the VBA code for your add-in. For example, you might want to create a simple
function that you can use in Excel.

2021-2024 Pg. No.58


BRAINALYST - VBA SERIES

• Save the Workbook as an Add-In:


• Save your Excel workbook as an add-in. To do this, go to File > Save As, choose a location, and
select Excel Add-In (*.xlam) as the file type. Save the file.

• Load the Add-In:


• To use the add-in in Excel, you need to load it.
• Go to File > Options > Add-Ins.
• In the “Manage” dropdown at the bottom, select “Excel Add-Ins” and click “Go...”.
• Click “Browse” and select your saved add-in file.
• Click “OK” to load the add-in.

• Use the Add-In Functions:


• Now, you can use the functions or features provided by your add-in in any Excel
workbook. For example, if your add-in has a function called MyCustomFunction,
you can use it in a cell like =MyCustomFunction(A1).

• Built-In Library for Add-Ins:

• When you create an add-in, it essentially becomes a library of functions that you can use across
multiple workbooks. You can organize your add-in code into multiple modules within the VBA
editor to create a more structured library.

• To do this:
• Organize Code into Modules:
• In the VBA editor, you can create additional modules (right-click on the project,
choose Insert, and then Module) to organize your code into logical units.
Pg. No.59 2021-2024
BRAINALYST - VBA SERIES

• Export/Import Modules:
• You can export individual modules or the entire project as .bas files and then
import them into other projects. This helps in reusing code.

• Create User Forms:


• If your add-in includes user interfaces, you can create user forms (right-click on
the project, choose Insert, and then UserForm) to provide a more user-friendly
experience.

• Document Your Code:


• Use comments and documentation within your code to make it easier for others
(or yourself) to understand and use your add-in.

Connecting Excel to MS Access involves using VBA (Visual Basic for Applications)
to establish a connection, execute SQL queries, and retrieve data.
• Step 1: Add Microsoft ActiveX Data Objects Library Reference
• Open Excel and press ALT + F11 to open the Visual Basic for Applications (VBA) editor.

• Go to Tools -> References.


• Scroll down and check “Microsoft ActiveX Data Objects x.x Library” (where x.x is the
version number).

• Step: 1 Add ado reference


• Step2: Create connections object
• Step3: Create record set object
• Step4: Write your sql query
• Step5: Pass your connection object and sql string to record set object
• Step 6: Get field names/headers

2021-2024 Pg. No.60


BRAINALYST - VBA SERIES

• Step7: save the output date


• Step 8: close record set and close connection

• Step 1: Write VBA Code to Connect Excel to MS Access:

• Conn: This variable is declared to represent the ADO connection object. It will be used to
establish a connection to the Access database.

• Rs: This variable is declared to represent the ADO recordset object. It will be used to store
and manipulate the results of SQL queries.

• StrConn: This variable is declared to store the connection string, which contains informa-
tion about the database to which you want to connect.

• CreateObject(“ADODB.Connection”): This line creates a new instance of the ADO Connection


object. This object is used to establish a connection to a data source, in this case, the Access
database.

• StrConn: This line defines the connection string. It specifies the OLE DB provider (Microsoft.
ACE.OLEDB.12.0 for Access), the data source (path to the Access database), and additional
connection properties.

• Conn.Open strConn: This line opens the connection to the Access database using the con-
nection string defined earlier.

• ExecuteSQLQuery: This line calls a function or subroutine named ExecuteSQLQuery. This is


a placeholder for the part of your code where you will write and execute SQL queries on the
connected Access database.

Pg. No.61 2021-2024


BRAINALYST - VBA SERIES

• Step 3: Execute SQL Query Using Recordset Object

• Set rs = CreateObject(“ADODB.Recordset”): This line creates a new instance of the ADO Re-
cordset object (rs). The Recordset object is used to store and manipulate the results of an
SQL query.

• strSQL: This variable stores the SQL query that will be executed. In this example, it selects all
columns (*) from a table named YourTableName. You should replace YourTableName with
the actual name of the table and customize the SQL query based on your needs.

• rs.Open strSQL, conn: This line executes the SQL query on the connected database using
the Open method of the Recordset object. It uses the SQL query (strSQL) and the previously
established connection object (conn). After this line, the Recordset (rs) contains the result
set from the database.

• ProcessResults: This line calls a function or subroutine named ProcessResults. This is a


placeholder for the part of your code where you would handle and process the results ob-
tained from the SQL query. For example, you could output the data to an Excel worksheet,
manipulate it, or perform any other desired operations.

• rs.Close: This line closes the Recordset object to release any resources associated with it
after processing the results.

• conn.Close: This line closes the connection to the database, freeing up resources.

• Step 4: Process Results and Output to Excel

2021-2024 Pg. No.62


BRAINALYST - VBA SERIES

• currentRow: This variable keeps track of the current row in the Excel worksheet where the
data will be output.

• Do Until rs.EOF: This initiates a loop that continues until the end of the Recordset (rs) is
reached. It means the loop will iterate through each record in the result set.

• Cells(currentRow, 1).Value = rs(“FieldName1”): This line assigns the value of the field named
“FieldName1” from the current record in the Recordset to the cell in the current row and the
first column (Column A) of the Excel worksheet.

• Cells(currentRow, 2).Value = rs(“FieldName2”): Similarly, this line assigns the value of the
field named “FieldName2” to the cell in the current row and the second column (Column B)
of the Excel worksheet. You can add more lines like these for additional fields.

• currentRow = currentRow + 1: This increments currentRow to move to the next row in the
Excel worksheet.

• rs.MoveNext: This moves the Recordset to the next record in the result set. The loop contin-
ues until all records have been processed.

• Step 10: Close Recordset and Connection

Pg. No.63 2021-2024


BRAINALYST - VBA SERIES

• Performance Optimization in VBA Excel

1. Efficient Coding Practices:

a. Use Explicit Data Types:

• Declare variables with specific data types (e.g., Integer, Long) to reduce memory usage and
improve performance.

b. Optimize Loops:

• Use the For...Next loop for known iterations and the Do...Loop for situations where the num-
ber of iterations isn’t known in advance.
• Minimize loop iterations and avoid unnecessary nested loops.

c. Avoid Variant Data Type:

• Be explicit about variable types to prevent automatic conversion to the Variant data type,
which can slow down code execution.

d. Limit the Use of Activate and Select:

• Minimize the use of Activate and Select methods, as they can slow down code and are often
unnecessary.

e. Disable Screen Updating:

• Use Application.ScreenUpdating = False to prevent the screen from updating during code
execution, improving performance.

2021-2024 Pg. No.64


BRAINALYST - VBA SERIES

2. Avoiding Common Pitfalls:


a. Avoid Using Volatile Functions Excessively:

• Volatile functions (e.g., NOW(), TODAY()) recalculate every time any cell changes, impact-
ing performance. Use them judiciously.

b. Limit the Use of INDIRECT Function:

• INDIRECT is a volatile function that can cause performance issues, especially in large data-
sets. Minimize its use.

c. Optimize Worksheet Interactions:

• Reduce the number of interactions with worksheets, especially within loops. Read/write
data in bulk rather than cell by cell.

d. Avoid Overusing Copy and Paste:

• Minimize the use of Copy and Paste operations, especially in loops. Directly manipulate
data whenever possible.

e. Optimize String Manipulation:

• Concatenating strings in a loop can be inefficient. Instead, use techniques like StringBuilder
or an array to concatenate strings.

3. Speeding up VBA Code:


a. Array Operations:

• Use arrays for bulk data operations. Working with arrays is generally faster than individual
cell operations.

b. Use InStr instead of Like for String Comparisons:

• InStr function is often faster than using the Like operator for string comparisons.

c. Application.Calculation:

• Set Application.Calculation = xlCalculationManual during code execution and revert to au-


tomatic calculation afterward.

d. Use With Statements:

• Utilize With statements to reference objects efficiently, reducing the need to repeat the
object reference.

e. Optimize Error Handling:

• Minimize the use of On Error Resume Next. Instead, use structured error handling to catch
and handle specific errors.

f. Use Integer Instead of Long:

• If the range of values allows, use Integer data type instead of Long for faster execution.

Pg. No.65 2021-2024

You might also like