Brainalyst's VBA For Macros Guide
Brainalyst's VBA For Macros Guide
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
• 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.
• 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.
• Workshops and Seminars: Hands-on training sessions on the latest trends and technologies in
data science 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.
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.
• 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.
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
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.
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.
2021-2024
BRAINALYST - VBA SERIES
• 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.
• 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.
• 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.
• Now, you should see the Developer tab in the Excel Ribbon.
• 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.
• Code Window:
• The area where you write and edit Visual Basic 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.
• 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.
• 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.”
• 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.
• 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.
• 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.
• 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.”
• 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.”
• 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.
• 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.
• 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.
• 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.
• Explanation:
• This macro writes the value 12 into cell B3 of the active sheet using the Range property.
• 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.
• This macro selects the ranges B3:B5 and C5:C8 in the active sheet using the Select method.
• Copy/Paste:
• Explanation:
• This macro copies only the values (not formulas) from B3:B5 and pastes them into cells
starting from G3.
• Explanation:
• This macro copies the entire data from “Sheet1” to “Sheet2” in the active workbook.
• Explanation:
• This macro copies the entire row (5th row) from “Sheet1” and pastes it to the 7th row in
the same sheet.
• Explanation:
• This macro clears only the contents of cells in the range A2:B4.
• Explanation:
• This macro clears all formats and values from cells in the range A2:B4.
• Explanation:
• This macro moves the cursor to the leftmost non-blank cell in the active row.
• Explanation:
• This macro moves the cursor to the rightmost non-blank cell in the active row.
• Explanation:
• This macro moves the cursor to the last non-blank cell in the active 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.
• 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.
• 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.
• 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.
• 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.
• Else:
• If the condition specified after the If keyword is false, the code within the Else block
is executed.
• End If:
• Marks the end of the If...Then...Else block.
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.
• 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.
• 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.
• Additional Notes:
• Entry Condition:
• Unlike the Do While loop, the Do Until loop ensures that the code inside the loop
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.
• 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
• Sub ClearContentsOfActiveSheet():
• Sub: Indicates the beginning of a subroutine (macro).
• ClearContentsOfActiveSheet: Name of the subroutine.
• 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.
• 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.
• 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.
• 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
• Types:
• Example Function:
• In this example, AddNumbers is a function that takes two parameters (x and y) and
returns their sum.
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.
• Insert a UserForm:
• In the VBA editor, right-click on any object in the “Project Explorer” (usually on the left
side).
• Choose “Insert” -> “UserForm.”
• Set Properties:
• Select each control, and set its properties using the “Properties” window.
• You can change properties such as names, captions, default values, etc.
Userform
• 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.
• 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.
• To show the Userform, place a command button on your worksheet and add the fol-
lowing code line:
• 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.
• 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.
• 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:
• 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.
• Indexing:
• Arrays in VBA are zero-based, meaning the first element has an index of 0.
• Access elements using their index.
• 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.
• 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.
• Application:
• Storing data from a range in a worksheet into an array for efficient manipulation and
analysis.
Basic Algorithm of Sorting
• 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.
• 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.
• 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.
• 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.
• 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.
• 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.
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
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.
• 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.
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 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).
• 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.
• 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.
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 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.
• 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.
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:
• 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.
• 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.
• 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.
• 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.).
• 6. Filtering:
• Report Filter: Filters the entire Pivot Table based on selected criteria.
• Slicer: Visual filter for easy data filtering.
• Creating a PivotTable:
• Use the Pivot Table Wizard method to create a new Pivot Table.
• 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.
• 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.
Introduction to Add-ins:
• Definition: An Excel Add-in is a supplemental program that adds custom commands or features to
Microsoft Excel.
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.
• 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.
• 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.
6. Event Handlers:
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.
• 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.
• 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.
• 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.
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.
• 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.
• 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.
• 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.
• 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.
• 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.
• 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.
• Be explicit about variable types to prevent automatic conversion to the Variant data type,
which can slow down code execution.
• Minimize the use of Activate and Select methods, as they can slow down code and are often
unnecessary.
• Use Application.ScreenUpdating = False to prevent the screen from updating during code
execution, improving performance.
• Volatile functions (e.g., NOW(), TODAY()) recalculate every time any cell changes, impact-
ing performance. Use them judiciously.
• INDIRECT is a volatile function that can cause performance issues, especially in large data-
sets. Minimize its use.
• Reduce the number of interactions with worksheets, especially within loops. Read/write
data in bulk rather than cell by cell.
• Minimize the use of Copy and Paste operations, especially in loops. Directly manipulate
data whenever possible.
• Concatenating strings in a loop can be inefficient. Instead, use techniques like StringBuilder
or an array to concatenate strings.
• Use arrays for bulk data operations. Working with arrays is generally faster than individual
cell operations.
• InStr function is often faster than using the Like operator for string comparisons.
c. Application.Calculation:
• Utilize With statements to reference objects efficiently, reducing the need to repeat the
object reference.
• Minimize the use of On Error Resume Next. Instead, use structured error handling to catch
and handle specific errors.
• If the range of values allows, use Integer data type instead of Long for faster execution.