Brainalyst's Macros Book - VBA For Macros in Excel
Brainalyst's Macros Book - VBA For Macros in Excel
Create a New Macro: In the VBA Editor, click on "Insert" in the menu and choose "Module."
It will create a new module where you can write your macro code.
Write the Macro Code: Now, you can start writing your macro code in the empty module.
The code should be written in VBA. If you are new to VBA, don't worry; it follows a
straightforward syntax.
Save the Macro: After writing the macro code, close the VBA Editor and save your
workbook as a macro-enabled workbook with the extension ".xlsm." This file format
allows macros to be saved within the workbook.
Run the Macro: To run the macro, go back to the worksheet where you want the macro to
take effect. Press "ALT + F8" to open the "Macro" dialog box. Select the macro you
created and click "Run."
Excel Macros and VBA / 03
Assign a Shortcut (Optional): If you plan to use the macro frequently, you can assign a
keyboard shortcut for quick access. To do this, go back to the VBA Editor, select the
macro from the left pane, and click on "Tools" > "Macro" > "Options." Here, you
can assign a shortcut key.
Avoid Select and Activate: Refrain from using the "Select" and "Activate" methods as
much as possible. Instead, work directly with objects and ranges in VBA without selecting
them first. This speeds up the code execution and reduces the risk of errors.
Optimize Loops and Code: If your macro involves loops or extensive calculations,
optimize the code to run efficiently. For instance, consider turning off screen updating
and calculation during the macro execution.
Comment Your Code: Add comments to your code to explain the purpose of each
section and any complex logic. This will help you and other users understand the code
better when reviewing or modifying it later.
Test Thoroughly: Before deploying your macro, test it thoroughly on sample data to
ensure it performs as expected and doesn't produce any errors.
Backup Your Work: Always make a backup copy of your workbook before running a
new macro, especially if the macro performs significant changes to the data. By adhering
to these best practices, you can create macros that are robust, reliable, and easy to
maintain over time.
Modules:
The place where the code is written is in modules. There are no Modules because
this is a brand-new Workbook.
Navigate to Insert -> Module to insert a module. 'module1' is formed once a
module is inserted.
We can write VBA code inside the modules, and the code is written inside a
Procedure. A procedure or subroutine is a collection of VBA statements that tells
the programmed what to do.
Procedure
Procedures are collections of statements that Excel is told to execute collectively in
order to carry out a certain task. The activity completed may be relatively
straightforward or extremely challenging.
However, it is a good idea to divide difficult processes into simpler ones.
The two primary categories of Procedures are Function and Sub.
Function
Anywhere in your application, you can invoke a function, which is a collection of
reusable code. This avoids the need to repeatedly write the same code. This aids
programmers in breaking down a large programme into several small, manageable
functions.
VBA allows users to create custom functions in addition to built-in ones, and
statements are placed between Function and End Function.
Excel Macros and VBA / 05
Sub-procedures
Functions and sub-procedures function similarly. Functions may or may not return a
value, but sub procedures DO NOT. It IS POSSIBLE to call sub-procedures without
the call keyword.
Sub and End Sub statements are required to surround sub processes.
Variables- VBA
In VBA, a variable serves as a named memory location that allows for the storage
of data that may change during the script's execution. To adhere to the correct naming
conventions for variables, it is essential to follow these fundamental guidelines:
The variable name must always begin with a letter.
Avoid using special characters such as spaces, periods, and exclamation points, as
well as symbols like @, &, $, or # in the variable's name.
Ensure that the length of the variable's name does not exceed 255 characters.
It is crucial to refrain from using reserved keywords specific to Visual Basic as variable
names.
Syntax:
Syntax in VBA, you need to declare the variables before using them.
Dim <variable_name> As <variable_type>>
Data Types
Numerous VBA data types can be categorised into two basic groups: numeric data
types and non-numeric data types.
Types of Numeric Data
The numeric data types and the permitted range of values are shown in the following table.
Excel Macros and VBA / 06
Constant VBA
In VBA, a constant serves as a named memory location that stores a fixed value,
maintaining its unchangeable nature throughout the script's execution. Unlike variables,
constants retain their assigned value and cannot be altered during the program's
runtime. Any attempt to modify a constant's value results in an error, leading to the
termination of the script's execution. To declare a constant, the same syntax used for
variables is employed.
To ensure adherence to the naming conventions for constants, consider the
following guidelines:
The constant's name must commence with a letter.
Special characters, including spaces, periods (.), exclamation marks (!),
as well as @, &, $, #, are strictly prohibited in the constant's name.
The length of the constant's name should not exceed 255 characters.
To prevent conflicts with language-specific commands, it is crucial to avoid utilizing
reserved keywords in Visual Basic as constant names.
Operator –VBA excel
A straightforward formula can be used to define an operator: 4 + 5 equals 9. In this
case, the operands are 4 and 5, and the operator is +. The following operator types
are supported by VBA:
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Concatenation Operators
Syntax:
InputBox(Prompt, [Title], [Default], [XPos], [YPos], [HelpFile], [Context])
Parameters:
Prompt: This is a mandatory parameter representing the message displayed in the
input box. It provides guidance to the user regarding the expected input. The prompt
can be up to 1024 characters long and can span multiple lines using the carriage return
character (Chr(13)) or linefeed character (Chr(10)).
Title (Optional): You can optionally specify a custom title for the input box dialog. If left
empty, the default title will display the application's name. The title should be a string
expression.
Default (Optional): This parameter allows you to suggest a default value that appears
in the input box, providing a user-friendly hint about the expected input format. The
default can be a string expression.
XPos (Optional): Represents the horizontal position of the input box relative to the left side
of the screen. If not specified, the input box will be horizontally centered. XPos is a
numeric expression.
YPos (Optional): Indicates the vertical position of the input box relative to the top of the
screen. If not specified, the input box will be vertically centered. YPos is also a numeric
expression.
Excel Macros and VBA / 07
HelpFile (Optional): If you have context-sensitive help related to the input box, you can
provide the HelpFile parameter, specifying the help file to be used. HelpFile should be
a string expression.
Context (Optional): When providing the HelpFile parameter, you can also specify the
Context parameter, which represents the help context number relevant to the specific
input box. Context is a numeric expression.
Example:
Let's create a very basic macro that simply picks a cell and enters the word "Excel" there.
While recording this macro, I am using the text "Excel," but feel free to substitute your
name or any other text you choose.
VBA Code:
Step-by-step:
Press ALT + F11 to open the VBA editor.
Click Insert > Module to add a new module.
Copy and paste the code into the module.
Close the VBA editor.
Press ALT + F8 to open the macro dialog box.
Select the "AutofitColumnsAndRows" macro from the list and click "Run."
2. Remove Duplicates:
This macro will remove duplicate values from the selected range in the active worksheet.
VBA Code:
Excel Macros and VBA / 09
Step-by-step:
Open the VBA editor and add a new module.
Copy and paste the code into the module.
Close the VBA editor.
Select the range containing the data from which you want to remove duplicates.
Press ALT + F8 to open the macro dialog box.
Select the "RemoveDuplicates" macro from the list and click "Run."
How to Use:
Make sure that the source data is in "Sheet1," starting from cell A1 (as shown in
the sample dataset).
Run the "SummarizeDataAndCreatePivotTable" macro by pressing Alt + F8,
selecting the macro, and clicking "Run."
The macro will summarize the sales data and create a pivot table in "Sheet1."
Excel Macros and VBA / 12
How to Use:
Make sure that the source data is in "Sheet1," starting from cell A1 (as shown in
the sample dataset).
Run the "FilterData" macro by pressing Alt + F8, selecting the macro, and clicking "Run."
The macro will apply an AutoFilter to the data in "Sheet1" and filter the data to
show only employees from the HR department.
How to Use:
Make sure that the source data is in "Sheet1," starting from cell A1 (as shown in
the sample dataset).
Run the "CopyFilteredData" macro by pressing Alt + F8, selecting the macro, and
clicking "Run."
The macro will apply an AutoFilter to the data in "Sheet1," filter the data to show only
employees from the HR department, and then copy the filtered data to a new sheet
named "FilteredData."
How to Use:
Press ALT + F11 to open the VBA editor.
Click Insert > Module to add a new module.
Copy and paste the code into the module.
Close the VBA editor.
Press ALT + F8 to open the macro dialog box.
Select the " createpivottable " macro from the list and click "Run."
Excel Macros and VBA / 14
How to Use:
Press ALT + F11 to open the VBA editor.
Click Insert > Module to add a new module.
Copy and paste the code into the module.
Close the VBA editor.
Press ALT + F8 to open the macro dialog box.
Select the " CalculateAge " macro from the list and click "Run."
Excel Macros and VBA / 15
How to Use:
Make sure that the source data is in "Sheet1," starting from cell A1 (as shown in the
sample dataset).
Run the "ApplyConditionalFormatting" macro by pressing Alt + F8, selecting the macro,
and clicking "Run."
The macro will apply conditional formatting to the "Salary" column and highlight
salaries greater than 50000 in red.
Sample Dataset:
Assume the following table represents our sample dataset for product sales data:
Excel Macros and VBA / 16
How to Use:
Make sure that the source data is in "Sheet1," starting from cell A1 (as shown in the
sample dataset).
Run the "CreateBarChart" macro by pressing Alt + F8, selecting the macro, and
clicking "Run."
The macro will create a new chart sheet named "SalesChart" and generate a bar chart
to visualize the quantity sold for each product.
How to Use:
Make sure that the source data is in "Sheet1," starting from cell A1 (as shown in the
sample dataset).
Run the "CreateDataValidationList" macro by pressing Alt + F8, selecting the macro,
and clicking "Run."
The macro will create a data validation list for the "Product" column, allowing users
to choose from a list of products in the cells.
How to Use:
Open your Excel workbook.
Press Alt + F11 to open the Visual Basic for Applications (VBA) editor.
In the VBA editor, go to Insert > Module to insert a new module.
Paste the provided VBA code into the module.
Close the VBA editor (Alt + Q) to return to Excel.
In your workbook, go to the sheet where you want to generate random numbers
(e.g., "Sheet1").
Run the "GenerateRandomNumbers" macro by pressing Alt + F8, selecting the
macro, and clicking "Run."
The macro will generate random numbers between 1 and 100 in column E, starting
from cell E2 (as shown in the code), for the specified range.
Excel Macros and VBA / 18
Instructions:
Open your Excel workbook that contains the sample dataset in "Sheet1."
Press Alt + F11 to open the Visual Basic for Applications (VBA) editor.
In the VBA editor, go to Insert > Module to insert a new module.
Paste the provided VBA code into the module.
Close the VBA editor (Alt + Q) to return to Excel.
How to Use:
Make sure that your dataset is in "Sheet1," starting from cell A1 (as shown in
the example dataset).
Run the "SummarizeSalesData" macro by pressing Alt + F8, selecting
"SummarizeSalesData," and clicking "Run."
Conclusion
Excel macros, powered by VBA, provide an incredible way to automate tasks, save time,
and extend the functionality of Microsoft Excel. With the ability to write custom code,
users can easily tailor Excel to suit their specific needs and tackle complex data
processing challenges. Whether you are a beginner or an experienced user, learning
VBA and mastering the art of Excel macros can significantly boost your productivity
and proficiency with this widely-used spreadsheet software.