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

Slides - VBA

Uploaded by

ranjit.k25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Slides - VBA

Uploaded by

ranjit.k25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 167

WHAT IS VBA

WHAT IS VBA NOTES


.
Link

Havish M Consulting ©
WHAT IS VBA

Is available on Windows and MAC

Still supported by Windows, but no updates

Havish M Consulting ©
UNDERSTANDING VBA

Developed and Owned by Microsoft

Event-driven tool to build custom


macrinstructions

Is NOT a stand-alone program

Can create GUI, UDF, access


Windows API, and automate
computer processes
Havish M Consulting ©
WHAT YOU CAN DO WITH VBA

Write macros: Macros allow financial professionals such as accountants, commercial bankers, investment
bankers, research analysts, salesmen, traders, portfolio managers, clerks, and administrators to analyze and adjust
huge amounts of data quickly.
Update data: You can use VBA in Excel to create and maintain complex trading, pricing, and risk-management
models, to forecast sales and earnings, and to generate financial ratios.

Perform scenario analysis: You can create various portfolio management and investment scenarios with Visual
Basic for Applications. This includes filtering through situations that may impact outcomes differently.

Organize information: You can also use VBA to produce lists of customers’ names or other content, to create
invoices, forms and charts, to analyze scientific data, and to manage data display for budgets and forecasting.

Be unconventional: VBA can be used to copy and paste values, adjust cell styles for an entire workbook, and
strike accelerator keys. You can perform very normal tasks in an easier, automated manner.

Prompt action: VBA can be used to interact with users. You might need a user's input for their first and last
names to be placed on a form. VBA prompts a user in a way that makes this input unavoidably mandatory.

Havish M Consulting ©
BLOCKED BY DEFAULT NOTES
Link

Havish M Consulting ©
VBA VS MACROS NOTES
VBA is the language.
Macros is a general computing term which
means performing steps.

For our sake – they are interchangeable.

Havish M Consulting ©
MACROS VS RPA NOTES
Unlike macros, which can only interface with a
single program at a time at the object layer,
RPA can engage with numerous apps
simultaneously.

RPA is more dynamic than macros, which are


fixed and linear.

Havish M Consulting ©
MACRO RECORDER NOTES
. Link

Havish M Consulting ©
MACROS IN SALESFORCE NOTES
. Link

Havish M Consulting ©
RPA LANDSCAPE NOTES
. Link

Havish M Consulting ©
NO CTRL + Z NOTES
Macros CANNOT be undone using Ctrl + Z.

Also,
After running a Macro, NO PREVIOUS ACTION
can be undone.

Step 1: Action (Added a Column)


Step 2: Action (Change cell colors)
Step 3: Action (Write a Formula)
Step 4: Run Macro (Ctrl + Z will NOT allow you to undo Step 1 – 3)

Havish M Consulting ©
OPTION TO UNDO MACROS NOTES
. Link

Havish M Consulting ©
VERSIONS ON EXCEL AUTOSAVE NOTES
. Version
history works
if files are set
to Autosave
and are on
OneDrive

Havish M Consulting ©
INTERFACE
ENABLE DEVELOPER TAB NOTES
File >
Options >
Customize Ribbon
> Developer
(Enable)

Note:
Need to enable only 1
time on YOUR computer
Needs to be done
SEPARATELY for Excel,
Word, PowerPoint
You can STILL write /
run codes if Developer is
NOT visible

Havish M Consulting ©
OPEN VISUAL BASIC (ALT + F11) NOTES
Developer >
Visual Basic

2 1

Havish M Consulting ©
PROJECT EXPLORER AND PROPERTIES WINDOW NOTES
Note:
There is ONE
Project Explorer
common VBA
interface
ALL Excel files
currently open on
your system will be
visible here

Properties Window

Havish M Consulting ©
PROJECT EXPLORER AND PROPERTIES WINDOW NOTES
Project Explorer:
Ctrl + R

Properties
Window:
F4

Havish M Consulting ©
INSERT MODULE NOTES
Select Correct File
>
Insert >
Module

Havish M Consulting ©
INSERT MODULE NOTES
Note:
Module names can be
changed – spaces
NOT allowed
One workbook can
have multiple
modules
Each module can
have multiple codes

Havish M Consulting ©
CODE LOCATION NOTES
Codes can be in:
Module
Sheet
Workbook

Havish M Consulting ©
CODE SYNTAX NOTES
Spaces, Lines and
Indentation has NO
Starts and End impact
with
Sub and End Sub
Options
appear after
dot notation (.)
Intellisense is
available
(code completion)

Havish M Consulting ©
CODE SYNTAX - IDE NOTES
Visual Studio with
Intellisense

Havish M Consulting ©
CODE SYNTAX NOTES
Ctrl + Space
Get List of options

Tab
Select

Space
Select and Add Space

Havish M Consulting ©
RUN MACROS FROM VBA WINDOW

Select Code and Use Reset whenever


Run (F5) you get an error

Havish M Consulting ©
RUN MACROS WITH DEVELOPER > MACROS > RUN

Havish M Consulting ©
RUN MACROS FROM A SHAPE

Havish M Consulting ©
RUN MACROS FROM QAT

Can also use


Alt + (Number)

Havish M Consulting ©
SAVE AS XLSM NOTES
Both .xlsm
and .xlsb can save
Macros

Havish M Consulting ©
SAVE AS XLSM NOTES
Note:
You can STILL run
Macros in
other .xlsx files as
long as the Macro
file is open

Havish M Consulting ©
F2 - OBJECT BROWSER

Havish M Consulting ©
COPY CODES FROM
INTERNET
SEARCH GOOGLE NOTES

Havish M Consulting ©
STACK OVERFLOW NOTES
Reading other
questions +
answers is a great
way of learning

Link

Havish M Consulting ©
GENAI NOTES

Havish M Consulting ©
STACK OVERFLOW NOTES

Note:
Note:
Deletes permanently

KILL is used to delete files

Be careful that your code does NOT use KILL unless you
know exactly what it is supposed to do

Sub DeleteFile()
Dim FilePath As String
FilePath = "C:\Path\To\Your\File.txt" 'Specify the path to the file you want to delete

If Dir(FilePath) <> "" Then 'Check if the file exists


Kill FilePath 'Delete the file
MsgBox "File deleted successfully.", vbInformation
Else
MsgBox "File not found.", vbExclamation
End If
End Sub

Havish M Consulting ©
PROGRAMMING
BASICS
CODE SYNTAX NOTES
Spaces, Lines and
Indentation has NO
Starts and End impact
with
Sub and End Sub
Options
appear after
dot notation (.)
Intellisense is
available
(code completion)

Havish M Consulting ©
CODE SYNTAX NOTES
x=4 Python indents are
MUST
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is exactly 5")
else:
print("x is less than 5")

Havish M Consulting ©
OBJECT MODEL NOTES

Havish M Consulting ©
OBJECT MODEL NOTES
VBA is object based
not fully OOP

Link

Havish M Consulting ©
DATA TYPES NOTES

Havish M Consulting ©
DATA TYPES NOTES

Havish M Consulting ©
DATA TYPES NOTES
The Variant data type is automatically specified if you Link
don't specify a data type when you declare a constant,
variable, or argument.

Variables declared as the Variant data type can contain


string, date, time, Boolean, or numeric values, and can
convert the values that they contain automatically.

Numeric Variant values require 16 bytes of memory


(which is significant only in large procedures or complex
modules), and they are slower to access than explicitly
typed variables of any other type.

You rarely use the Variant data type for a constant.


String Variant values require 22 bytes of memory.
Havish M Consulting ©
DECLARATION (DIM) NOTES
Description Format Example
Basic variable Dim [variable name] As [Type] Dim count As Long
Dim amount As Currency
Link
Dim name As String
Dim visible As Boolean

Fixed String Dim [variable name] As String * [size] Dim s As String * 4


Dim t As String * 10 Dimension
Variable Declaration
Variant Dim [variable name] As Variant Dim var As Variant
Dim [variable name] Dim var

Object using Dim and New Dim [variable name] As New [object type] Dim coll As New Collection
Dim coll As New Class1

Object using Dim, Set and Dim [variable name] As [object type] Dim coll As Collection
New Set [variable name] = New [object type] Set coll = New Collection

Dim coll As Class1


Set coll = New Class1

Static array Dim [variable name] Dim arr(1 To 6) As Long


([first] To [last] ) As [Type]

Dynamic array Dim [variable name]() As [Type] Dim arr() As Long


ReDim [variable name]([first] To [last]) ReDim arr(1 To 6)

External Library Dim [variable name] As New [item] Dim dict As New Dictionary
(Early Binding)*
External Library Dim [variable name] As [item] Dim dict As Dictionary
(Early Binding using Set)* Set [variable name] = New [item] Set dict = New Dictonary

External Library Dim [variable name] As Object Dim dict As Object


(Late Binding) Set [variable name] = Set dict = CreateObject("Scripting.Dictionary")
CreateObject("[library]")

Havish M Consulting ©
DECLARATION (DIM) NOTES
Option Explicit
Best practice – makes it
mandatory to declare
variables

= is for assignment,
NOT equality

Havish M Consulting ©
TYPES OF PROCEDURES NOTES
Sub ShowMessage() Sub
End Sub
MsgBox "Hello, Havish!"
Function
End Sub
End Function

Function AddNumbers(num1 As Integer, num2


As Integer) As Integer
AddNumbers = num1 + num2
End Function

Havish M Consulting ©
TYPES OF PROCEDURES NOTES
Public Link
Is the default

Private
Does not appear in Macros Window
Cannot run in other Modules (but can use
Application.Run to execute)

Application.Run “Sub Name”

Havish M Consulting ©
HANDLING ERRORS NOTES
Cannot continue
working on Excel till
we Reset the code

Havish M Consulting ©
HANDLING ERRORS NOTES
There are three types
of errors in VBA:
Syntax
Compilation
Runtime

Link

Havish M Consulting ©
HANDLING ERRORS NOTES
Sub ExampleDebugPrint()
View >
Dim x As Integer Immediate Window
Dim y As Integer
(Ctrl + G)
Dim z As Integer

x = 10
y = 20

' Perform some operations


z=x+y

' Print the values of variables


Debug.Print "Value of x: " & x
Debug.Print "Value of y: " & y
Debug.Print "Sum of x and y: " & z
End Sub

Havish M Consulting ©
HANDLING ERRORS NOTES
Link

Link

Havish M Consulting ©
BREAK INTO 2 LINES NOTES
Sub Example() [space] [underscore]
Dim message As String
message = "Hello, " & _
"Havish!"
MsgBox message
End Sub

Havish M Consulting ©
COMMENTS NOTES
Sub Example() Comments are
'Declaring message green in color
Dim message As String
message = "Hello, " & _ Can also come at
"Havish!" the end of a line
MsgBox message 'Show Result
End Sub

Havish M Consulting ©
COMMENTS

Havish M Consulting ©
ACTIVE WORKBOOK AND WORKSHEET NOTES
Sub AddValueToCellA1()
Dim wb As Workbook Sub AddValueToCell()
Dim ws As Worksheet Dim wb As Workbook
Dim ws As Worksheet
' Set the active workbook as wb
Set wb = ActiveWorkbook ' Set the active workbook as wb
Set wb = Workbooks("DE
SHAW.xlsm")
' Set the active worksheet from wb as
ws
Set ws = wb.ActiveSheet ' Set the active worksheet from the
workbook
Set ws = wb.Sheets("CALCULATION")
' Add a value to cell A1
ws.Range("A1").Value = "Hello,
World!" ' Add a value to cell A1
End Sub ws.Range("A1").Value = "Hello,
World!"
End Sub

Havish M Consulting ©
MESSAGEBOX NOTES
Link

Havish M Consulting ©
MESSAGEBOX AND INPUTBOX NOTES
Sub CalculateFutureValue()
Dim principal As Double
Dim rate As Double
Dim periods As Integer
Dim futureValue As Double

' Input principal amount


principal = InputBox("Enter the principal amount:")

' Input interest rate


rate = InputBox("Enter the annual interest rate (as a percentage):")

' Input number of periods


periods = InputBox("Enter the number of periods:")

' Convert interest rate from percentage to decimal


rate = rate / 100

' Calculate future value


futureValue = principal * (1 + rate) ^ periods

' Display the result using a MessageBox


MsgBox "The future value of the investment is: " & futureValue
End Sub

Havish M Consulting ©
FORMATTER NOTES
Link

Havish M Consulting ©
RECORD MACROS
RECORD MACROS NOTES
While recording
can toggle
between Absolute
and Relative

Absolute Reference Relative Reference

Havish M Consulting ©
START RECORDING NOTES
Macros can be
saved in:
Personal Macro
Workbook (accessible
across ALL Excel files)
New Workbook
This Workbook

Do NOT assign
shortcuts as it can
conflict with existing
shortcuts

Havish M Consulting ©
STOP RECORDING NOTES

Havish M Consulting ©
RECORD MACROS NOTES
Personal Macro
Workbook
Accessible across ALL
Excel files on your
computer

Havish M Consulting ©
WORK ON VBA AND EXCEL AT SAME TIME (USE WINDOWS + LEFT/RIGHT)

Havish M Consulting ©
ABSOLUTE VS RELATIVE TASK

Write Sum in C5
Copy Formula till H5

Havish M Consulting ©
ABSOLUTE
Sub Absolute_Copy_Paste()
Selection.FormulaR1C1 = "=SUM(R[1]C:R[2]C)"
Selection.Copy Sub Absolute_Ctrl_R()
Range("C5:H5").Select Selection.FormulaR1C1 = "=SUM(R[1]C:R[2]C)"
ActiveSheet.Paste Range("C5:H5").Select
End Sub Selection.FillRight
End Sub

Sub Absolute_Copy_Drag()
Selection.FormulaR1C1 = "=SUM(R[1]C:R[2]C)"
Selection.AutoFill Destination:=Range("C5:H5"), Sub Absolute_Jump_To_Last_Cell()
Type:=xlFillDefault
Selection.FormulaR1C1 = "=SUM(R[1]C:R[2]C)"
Range("C5:H5").Select
Range("C6").Select
End Sub
Selection.End(xlToRight).Select
Range("H5").Select
Range(Selection, Selection.End(xlToLeft)).Select
Selection.FillRight
End Sub

Havish M Consulting ©
RELATIVE
Sub Relative_Copy_Paste() Sub Relative_Ctrl_R()
Selection.FormulaR1C1 = "=SUM(R[1]C:R[2]C)" Selection.FormulaR1C1 = "=SUM(R[1]C:R[2]C)"
Selection.Copy ActiveCell.Range("A1:F1").Select
ActiveCell.Range("A1:F1").Select Selection.FillRight
ActiveSheet.Paste End Sub
End Sub

Sub Relative_Copy_Drag() Sub Relative_Jump_To_Last_Cell()


Selection.FormulaR1C1 = "=SUM(R[1]C:R[2]C)" Selection.FormulaR1C1 = "=SUM(R[1]C:R[2]C)"
Selection.AutoFill Destination:=ActiveCell.Range("A1:F1"), ActiveCell.Offset(1, 0).Range("A1").Select
Type:=xlFillDefault
Selection.End(xlToRight).Select
ActiveCell.Range("A1:F1").Select
ActiveCell.Offset(-1, 0).Range("A1").Select
End Sub
Range(Selection, Selection.End(xlToLeft)).Select
Selection.FillRight
End Sub

Havish M Consulting ©
FORMULAS NOTES
Sub FormulaStyle1() Formula2 is for
Selection.FormulaR1C1 = "=SUM(R[1]C:R[2]C)" Dynamic Array
End Sub formulas

Sub FormulaStyle2()
Selection.Formula = "=SUM(C6:C7)"
End Sub

Sub FormulaStyle3()
ActiveCell.Formula2R1C1 = "=SEQUENCE(10)"
End Sub

Havish M Consulting ©
GOOGLE SHEETS NOTES

Havish M Consulting ©
GOOGLE SHEETS NOTES

Havish M Consulting ©
GOOGLE SHEETS NOTES
/** @OnlyCurrentDoc */

function UntitledMacro() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('C5').activate();
spreadsheet.getCurrentCell().setFormula('=SUM(C6:C7)');
spreadsheet.getRange('C5:H5').activate();
spreadsheet.getRange('C5').copyTo(spreadsheet.getActiveRange(),
SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
};

Havish M Consulting ©
TYPESCRIPT

Havish M Consulting ©
TYPESCRIPT

Havish M Consulting ©
TYPESCRIPT NOTES
function main(workbook: ExcelScript.Workbook) {
let selectedSheet = workbook.getActiveWorksheet();
// Set range C5 on selectedSheet
selectedSheet.getRange("C5").setFormulaLocal("=SUM(C6:C7)");
// Paste to range C5:H5 on selectedSheet from range C5 on selectedSheet
selectedSheet.getRange("C5:H5").copyFrom(selectedSheet.getRange("C5"),
ExcelScript.RangeCopyType.all, false, false);
}

Havish M Consulting ©
TYPESCRIPT NOTES
Link

Havish M Consulting ©
PYTHON NOTES
import xlwings as xw

# Define the file path and name

file_path = r"C:\Users\havis\OneDrive\Desktop\VBA\Record Macro Python.xlsm"

# Connect to Excel and the workbook

app = xw.App(visible=False) # Set visible to True if you want to see Excel operate

book = app.books.open(file_path)

# Select the sheet

sheet = book.sheets["Test"]

# Write the initial formula in cell C5

sheet.range("C5").formula = "=SUM(C6:C7)"

# Copy the formula from C5 to D5 through H5, adjusting the row references

for col in range(4, 9): # From D (4) to H (8)

column_letter = chr(col + 64) # Convert column number to letter, where A = 65

formula = f"=SUM({column_letter}6:{column_letter}7)"

sheet.range(f"{column_letter}5").formula = formula

# Save and close the workbook

book.save()

book.close()

app.quit()

print("Formula written and copied with dynamic references successfully.")

Havish M Consulting ©
PYTHON NOTES
Link

Havish M Consulting ©
WRITE CODE
OPTIMIZATION NOTES
Tips to speed up code Link

Havish M Consulting ©
CALL SUB NOTES
Sub Mini01() Call is optional
MsgBox "Hello" But it is recommended for
readability
End Sub

Sub Mini02()
Sub can be called from
MsgBox "World" other modules as well
End Sub

Use Application.Wait to
Sub CallAll() wait before running next
line of code
Call Mini01
Application.Wait (Now + TimeValue("0:00:05"))
Call Mini02
End Sub

Havish M Consulting ©
TAKE VALUE TASK

Show Values in E9:E11 in


a MessageBox

Havish M Consulting ©
TAKE VALUE NOTES
Sub ShowSelectedRangeInMessageBox()
Dim selectedRange As Range
Dim cell As Range
Dim message As String

' Set the range to be E9:E11


Set selectedRange = Sheets("Fields").Range("E9:E11")

' Loop through each cell in the selected range and concatenate their values
For Each cell In selectedRange
message = message & cell.Value & vbCrLf
Next cell

' Display the message box with the concatenated values


MsgBox message
End Sub

Havish M Consulting ©
TAKE VALUE NOTES
Get Info using ?

Havish M Consulting ©
WRITE VALUE TASK

Write Checked, Pending,


Checked in G9:G11

Havish M Consulting ©
WRITE VALUE NOTES
Sub WriteValues()
Sheets("Fields").Range("G9").Value = "Checked" Sub WriteValues()
Sheets("Fields").Range("G10").Value = "Pending" Dim ws As Worksheet
Sheets("Fields").Range("G11").Value = "Checked" Dim values As Variant
End Sub Dim i As Integer

Sub WriteValues() Set ws = ThisWorkbook.Sheets("Fields")


Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Fields") ' Define the values
ws.Range("G9:G11").Value = values = Array("Checked", "Pending", "Checked")
Application.Transpose(Array("Checked", "Pending",
"Checked"))
End Sub ' Write values to cells G9 to G11
For i = 0 To UBound(values)
ws.Cells(9 + i, 7).Value = values(i)
Next i
End Sub

Havish M Consulting ©
WRITE VALUE NOTES
={"Checked";"Pending";"Checked"}

Havish M Consulting ©
WRITE VALUE TASK

Write Checked, Pending,


Checked in G9:G11 in a
closed file

Havish M Consulting ©
WRITE VALUE NOTES
Sub UpdateCells()
Dim xlApp As Object
.Range("G9").Value = "Checked"
.Range("G10").Value = "Pending"
Excel is opened
Dim xlBook As Object .Range("G11").Value = "Checked"
Dim filePath As String End With

' Path to your workbook ' Save changes and close the workbook
filePath = "C:\Users\havis\OneDrive\Desktop\VBA\ xlBook.Save
Financial_Statement.xlsm"
xlBook.Close

' Create a new Excel application


' Quit Excel
Set xlApp = CreateObject("Excel.Application")
xlApp.Quit

' Open the workbook


' Clean up
Set xlBook = xlApp.Workbooks.Open(filePath)
Set xlBook = Nothing
Set xlApp = Nothing
' Ensure Excel is visible
End Sub
xlApp.Visible = True

' Access the 'Fields' sheet and modify cells G9, G10,
G11
With xlBook.Sheets("Fields")

Havish M Consulting ©
WRITE VALUE NOTES
Sub UpdateCells()
Dim xlApp As Object
With xlBook.Sheets("Fields")
.Range("G9").Value = "Checked"
Excel is closed
Dim xlBook As Object .Range("G10").Value = "Pending"
Dim filePath As String .Range("G11").Value = "Checked"
End With
' Path to your workbook
filePath = "C:\Users\havis\OneDrive\Desktop\VBA\ ' Save changes and close the workbook
Financial_Statement.xlsm"
xlBook.Save
xlBook.Close SaveChanges:=True ' Ensure that changes
' Create a new Excel application are saved without prompting
Set xlApp = CreateObject("Excel.Application")
' Quit Excel
' Make Excel not visible xlApp.Quit
xlApp.Visible = False
' Re-enable alerts for future operations
' Disable alerts to prevent Excel from displaying xlApp.DisplayAlerts = True
messages
xlApp.DisplayAlerts = False
' Clean up
Set xlBook = Nothing
' Open the workbook
Set xlApp = Nothing
Set xlBook = xlApp.Workbooks.Open(filePath)
End Sub

' Access the 'Fields' sheet and modify cells G9, G10, G11

Havish M Consulting ©
WRITE VALUE NOTES

excel.com /x Opens new


instance of
Excel

Useful for working


with Power
Query Editor and
Excel parallelly

Havish M Consulting ©
WRITE VALUE NOTES
Excel is closed

Havish M Consulting ©
WRITE VALUE TASK

Copy E9:E11 in G9:G11

Havish M Consulting ©
PASTE VALUE NOTES
Sub CopyPasteFields()
Sheets("Fields").Range("E9:E11").Copy Destination:=Sheets("Fields").Range("G9")
End Sub

Sub Macro2()
Range("E9:E11").Select
Selection.Copy
Range("G9").Select
ActiveSheet.Paste
End Sub

Havish M Consulting ©
PASTE VALUE NOTES
=E9:E11

Havish M Consulting ©
WRITE SERIAL NUMBERS - LOOP TASK

Write 1 to 12 in D9:O9

Havish M Consulting ©
WRITE SERIAL NUMBERS - LOOP NOTES
Link

Havish M Consulting ©
WRITE SERIAL NUMBERS - LOOP NOTES

Havish M Consulting ©
WRITE SERIAL NUMBERS - LOOP NOTES
Sub EnterNumbers()
Dim userInput As Integer
Dim cell As Range
Dim startingCell As Range

' Prompt the user for input


userInput = InputBox("Enter the number of values To enter:")

' Set the starting cell


Set startingCell = ThisWorkbook.Sheets("M. Income sheet").Range("D9")

' Loop through and enter the numbers


For i = 1 To userInput
startingCell.Offset(0, i - 1).Value = i
Next i
End Sub

Havish M Consulting ©
WRITE SERIAL NUMBERS - EXCEL NOTES
= TRANSPOSE(SEQUENCE(12))
= SEQUENCE(,12)

Havish M Consulting ©
WRITE SERIAL NUMBERS - LOOP TASK

Write 1 to 9 in C3:C11

Havish M Consulting ©
WRITE SERIAL NUMBERS - LOOP NOTES
Sub WriteSerialNumbers()
lrow
Dim ws As Worksheet
Dim lastRow As Long lcol
Dim i As Long

' Set the worksheet


Set ws = ThisWorkbook.Sheets("S No") ' Change "Sheet1" to your sheet's name

' Find the last row in Column C


lastRow = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row

' Write serial numbers in Column A


For i = 3 To lastRow
ws.Cells(i, 2).Value = i - 2
Next i
End Sub

Havish M Consulting ©
WRITE SERIAL NUMBERS - EXCEL NOTES
=SEQUENCE(COUNTA(C:C)-1)

Havish M Consulting ©
WRITE SERIAL NUMBERS SKIP BLANKS - LOOP TASK

Write 1 to 9 in C3:C11

Havish M Consulting ©
WRITE SERIAL NUMBERS SKIP BLANKS - LOOP NOTES
Sub FillSerialNumbers()

' Find the last row in column C that has data


lastRow = Cells(Rows.Count, "C").End(xlUp).Row

' Start serial number from 1


serialNumber = 1

' Loop through rows from 3 to the last row


For i = 3 To lastRow
' Check if the cell in column C is blank
If Cells(i, "C").Value <> "" Then
' Write the serial number in column B
Cells(i, "B").Value = serialNumber

' Increment the serial number


serialNumber = serialNumber + 1
End If
Next i
End Sub

Havish M Consulting ©
WRITE SERIAL NUMBERS - LOOP TASK

Choose R/C and create


sequence with user
Input

Havish M Consulting ©
WRITE SERIAL NUMBERS - LOOP NOTES
Sub SNo()
If user_choice = "R" Then
GoTo line1
GoTo Line
GoTo line2 Else
For i = 1 To last_num Exit Sub
line1: Cells(i + 1, 1).Value = i MsgBox "Please enter R/C
user_choice = InputBox("Choose Next only!"
Row (R) / Column (C)")
MsgBox user_choice ElseIf user_choice = "C" End If
Exit Sub Then
End Sub
line2: For i = 1 To last_num
user_choice = InputBox("Choose Cells(1, i + 1).Value = i
Row (R) / Column (C)") Next

'validation for R / C End If


If user_choice = "R" Or
user_choice = "C" Then Else
MsgBox "Please enter a
'ask for last number number between 1 and 10!"
last_num = InputBox("How GoTo line2
many numbers?") End If

'validate last_num to be ElseIf user_choice = "r" Or


between 1 and 10 user_choice = "c" Then
If IsNumeric(last_num) And
last_num >= 1 And last_num <= MsgBox "Please enter in upper
10 Then case only!"

Havish M Consulting ©
FIND YTD TARGET - LOOP TASK

Find month where YTD


reaches 100000

Havish M Consulting ©
FIND YTD TARGET - LOOP NOTES
Sub CalculateYTD()
Dim ytdSum As Double
Dim currentValue As Double
Dim rowCount As Integer
Dim targetValue As Double

' Initialize variables


ytdSum = 0
rowCount = 2 ' Assuming data starts from row 2
targetValue = 100000

' Loop through the rows until YTD sum reaches 100,000
Do While ytdSum < targetValue
' Assuming the value for each row is in column A, change as necessary
currentValue = Cells(rowCount, 2).Value

' Add current value to YTD sum


ytdSum = ytdSum + currentValue

' Move to the next row


rowCount = rowCount + 1

' Check if we've reached the end of the data


If IsEmpty(Cells(rowCount, 1).Value) Then
MsgBox "YTD sum reached before hitting 100,000"
Exit Sub
End If
Loop

' Output the result


MsgBox "YTD sum reached 100,000 at row " & rowCount - 1 & ". YTD Sum: " & ytdSum
End Sub

Havish M Consulting ©
FIND YTD TARGET - LOOP NOTES

Havish M Consulting ©
FIND YTD TARGET - LOOP NOTES

Havish M Consulting ©
CONDITIONAL STATEMENT - IF TASK

Write a number in E11


with validations

Havish M Consulting ©
CONDITIONAL STATEMENT - IF NOTES

Havish M Consulting ©
CONDITIONAL STATEMENT - IF NOTES

Havish M Consulting ©
CONDITIONAL STATEMENT - IF
Sub EnterNumberInE11() Sheets("Fields").Range("E11").Value = number
Dim userInput As Variant Exit Sub ' Exit the loop if a valid number is entered
Else
' Prompt the user to enter a number MsgBox "Number must be between 5000 And 50000. Please try
userInput = InputBox("Please enter a number between 5000 And again.", vbExclamation, "Invalid Number"
50000 For cell E11:" & vbCrLf & "(You can click Cancel To abort)", "Enter End If
Number") Else
MsgBox "Input must be a number. Please try again.",
' Check if the user clicked Cancel vbExclamation, "Invalid Input"
If userInput = "" Then End If
MsgBox "Operation aborted.", vbInformation, "Cancelled"
Exit Sub ' Prompt the user to enter a number again
End If userInput = InputBox("Please enter a number between 5000 And
50000 For cell E11:" & vbCrLf & "(You can click Cancel To abort)", "Enter
' Loop until a valid number is entered Number")
Do
' Check if the input is a valid number ' Check if the user clicked Cancel
If IsNumeric(userInput) Then If userInput = "" Then
' Convert the input to a number MsgBox "Operation aborted.", vbInformation, "Cancelled"
Dim number As Double Exit Sub
number = CDbl(userInput) End If
Loop
' Check if the number is within the specified range End Sub
If number >= 5000 And number <= 50000 Then
' Set the value in cell E11

Havish M Consulting ©
UDF
'Function with single input
Function Square(myinput As Long)

Square = myinput ^ 2

End Function

'Function with 2 inputs


Function MyGST(myval As Single, gst_amt As Single)

MyGST = myval + (myval * (gst_amt / 100))

End Function

Function UoM(myval As Double, unit As String)

If unit = "Lakhs" Then


UoM = myval / 100000
Else
UoM = myval / 10000000
End If

End Function

Havish M Consulting ©
UDF NOTES
Functions do
NOT have
tooltips

Link

Havish M Consulting ©
UDF NOTES
Function Square(myinput As Long) Use UDF inside UDF

Square = myinput ^ 2
Link

End Function
IMPORTANT:
data type should be
SAME in both UDF
Function Test(myval As Long)

Test = Square(myval) + 2
UDF CANNOT be called
from Personal Macro
End Function Workbook

Havish M Consulting ©
UDF NOTES
Function CountErrors(cells As Range) As Long In VBA we CANNOT
use Excel functions
Dim cell As Range To use an Excel
For Each cell In cells function in VBA, we
use
Application.WorksheetFunct
If Application.WorksheetFunction.IsError(cell) = True Then ion

CountErrors = CountErrors + 1
Note:
End If
Function arguments are
Next mentioned as numbers, NOT
the actual argument

End Function

Havish M Consulting ©
UDF NOTES
List of worksheet functions available to Visual Link
Basic

Havish M Consulting ©
LAMBDA NOTES
'Function with single input
Function Square(myinput As Long)

Square = myinput ^ 2

End Function

=LAMBDA(myinput, myinput * myinput)

Havish M Consulting ©
LAMBDA NOTES

Havish M Consulting ©
LAMBDA NOTES

1 2 Add-ins >
Excel Labs >
Advanced
Formula
Environment
3
Can also import
GitHub Gist URL

Link
4

Havish M Consulting ©
LAMBDA
'Function with 2 inputs
Function MyGST(myval As Single, gst_amt As Single)

MyGST = myval + (myval * (gst_amt / 100))

End Function

=LAMBDA(myval, gst_amt, myval + myval * gst_amt / 100)

Havish M Consulting ©
LAMBDA
Function UoM(myval As Double, unit As String)

If unit = "Lakhs" Then


UoM = myval / 100000
Else
UoM = myval / 10000000
End If

End Function

=LAMBDA(myval, unit, IF(unit = "Lakhs", myval / 100000, myval / 10000000))

Havish M Consulting ©
COMBINE FILES
COMBINE FILES NOTES
Link

Havish M Consulting ©
COMBINE FILES TASK

Consolidate 4 Excel files

Havish M Consulting ©
COMBINE FILES
Sub ConsolidateExcelFiles() End If
Dim FolderPath As String ' Loop through all files in the DestSheet.Rows(RowIndex).Dele
folder te
Dim Filename As String ' Copy data from the
Filename = Dir(FolderPath & source sheet to the destination End If
Dim Sheet As Worksheet
"*.xlsx") sheet Next RowIndex
Dim DestSheet As Worksheet
Do While Filename <> "" Set SourceRange = End If
Dim LastRow As Long Sheet.Range("A1:Z" & LastRow)
' Open each workbook
Dim DestLastRow As Long Set DestRange =
Workbooks.Open ' Find the next file in the
Dim SourceRange As Range Filename:=FolderPath & DestSheet.Range("A" & folder
Dim DestRange As Range Filename DestLastRow)
Filename = Dir
Dim RowIndex As Long Set Sheet = ActiveSheet SourceRange.Copy
DestRange Loop
Dim FileIndex As Long
Dim isFirstFile As Boolean ' Find the last row in the ' Save the consolidated
source sheet ' Close the workbook
without saving changes workbook
' Specify the folder path LastRow = DestSheet.Copy
Sheet.Cells(Sheet.Rows.Count, Workbooks(Filename).Close
FolderPath = "C:\Users\havis\ "A").End(xlUp).Row SaveChanges:=False ActiveWorkbook.SaveAs
OneDrive\Desktop\VBA\ Filename:=FolderPath &
Consolidate\" "Consolidated.xlsx",
' Set destination start row ' Find and remove duplicate FileFormat:=xlOpenXMLWorkboo
based on isFirstFile flag first row in destination sheet k
' Create a new workbook for If DestLastRow > 1 Then
consolidation If isFirstFile Then ActiveWorkbook.Close
DestLastRow = 1 For RowIndex = SaveChanges:=False
Workbooks.Add DestLastRow To 2 Step -1
Set DestSheet = ActiveSheet isFirstFile = False
If MsgBox "Files have been
Else DestSheet.Cells(RowIndex, consolidated successfully!",
' Initialize isFirstFile flag DestLastRow = 1).Value = DestSheet.Cells(1, vbInformation
DestSheet.Cells(DestSheet.Rows 1).Value Then
isFirstFile = True .Count, "A").End(xlUp).Row + 1 End Sub

Havish M Consulting ©
READ SAME FOLDER – CHANGING FILE NAME
Sub ReadValueFromUnknownFile() ' Open the found workbook
Set SourceWorkbook =
Workbooks.Open(FolderPath & FileName)
Dim FolderPath As String
' Copy the value from A1 in the source
Dim FileName As String
workbook
Dim SourceWorkbook As Workbook
ThisWorkbook.Sheets(1).Range("A1").Value =
SourceWorkbook.Sheets(1).Range("A1").Value
' Specify the folder path (update with your actual ' Close the source workbook without saving
path) changes
FolderPath = "C:\Users\havis\OneDrive\Desktop\ SourceWorkbook.Close SaveChanges:=False
Files for Workshop\Same Folder Name - Changing
Else
File Name\Folder\"
MsgBox "No Excel file found in the folder."
End If
' Get the first Excel file found in the folder
(assumes there's only one)
FileName = Dir(FolderPath & "*.xlsx") End Sub

' If a file was found


If FileName <> "" Then
Havish M Consulting ©
USER FORMS
USER FORMS NOTES

Havish M Consulting ©
USER FORMS NOTES
Name
To call Macro

Caption
Visible on Form

Havish M Consulting ©
USER FORMS NOTES
Toolbox

Havish M Consulting ©
USER FORMS NOTES
Toolbox

Label
TextBox
ComboBox
ListBox
CheckBox
RadioButton
ToggleButton
Frame
CommandButton
TabStrip
MultiPage
ScrollBar
SpinButton
Picture

Havish M Consulting ©
USER FORMS NOTES

Havish M Consulting ©
USER FORMS NOTES
ShowModal (False)
Allows working on
Excel and UserForm at
the same time

Havish M Consulting ©
USER FORMS NOTES
Tab Order
Choose order of
selecting objects with
Tab and Shift Tab

Havish M Consulting ©
USER FORMS TASK

Create a UserForm to
take Vendor Name, GL
Code and Amount

Also Total at bottom

Havish M Consulting ©
ARRAYS
ARRAYS NOTES
Sub ReadingRange() Read and Debug

Dim rg As Range
Set rg = shData.Range("A1").CurrentRegion

Dim i As Long
For i = 1 To rg.Rows.Count
Debug.Print rg.Cells(i, 1).Value
Next i

End Sub
Havish M Consulting ©
ARRAYS NOTES
Sub ReadingRange2() Watch

Dim rg As Range
Set rg = shData.Range("A1").CurrentRegion

Dim arr As Variant


arr = rg.Value

End Sub

Havish M Consulting ©
ARRAYS NOTES
Right Click on arr >
Add Watch

BreakPoint at End
Subs

Havish M Consulting ©
ARRAYS NOTES
Sub ReadingRange3() Bound

Dim arr As Variant


arr = shData.Range("A1").CurrentRegion

Dim i As Long
For i = LBound(arr, 1) To UBound(arr, 1)
Debug.Print arr(i, 1), arr(i, 3), arr(i, 2)
Next i

End Sub
Havish M Consulting ©
ARRAYS NOTES
Sub ReadingRange4() Write Back

Dim arr As Variant


arr = shData.Range("A1").CurrentRegion

Dim i As Long
For i = LBound(arr, 1) To UBound(arr, 1)
Debug.Print arr(i, 1), arr(i, 1)
Next i

shData.Range("E1:G6").Value = arr

End Sub
Havish M Consulting ©
ARRAYS NOTES
Sub ReadingRange5() Change Array

Dim arr As Variant


arr = shData.Range("A1").CurrentRegion

Dim i As Long
For i = LBound(arr, 1) + 1 To UBound(arr, 1)
arr(i, 2) = arr(i, 2) + 10
'Debug.Print arr(i, 2) = arr(i, 2) - 10
Next i

'Clear Contents
'shData.Range("E1").CurrentRegion.ClearContents

'Write Back
shData.Range("E1:G6").Value = arr

End Sub
Havish M Consulting ©
ARRAYS NOTES
Sub ReadingRange6() Change Array
Dynamic
Dim arr As Variant
arr = shData.Range("A1").CurrentRegion

'Clear Contents
shData.Range("E1").CurrentRegion.ClearContents

Dim rowCount As Long, columnCount As Long


rowCount = UBound(arr, 1) '1 refers to the row
columnCount = UBound(arr, 2) ' 2 refers to the col

MsgBox rowCount
MsgBox columnCount

shData.Range("E1").Resize(rowCount, columnCount).Value = arr

End Sub
Havish M Consulting ©
INTEGRATION
EXCEL PPT, WORD, FOLDER, PIVOT TABLE, RIBBON, ZIP NOTES

Havish M Consulting ©
BINDING NOTES
Tools > References

Havish M Consulting ©
EARLY VS LATE BINDING NOTES
Link

Havish M Consulting ©
ADD-INS
OFFICE ADD-INS NOTES
Link

Havish M Consulting ©
OFFICE RIBBONX EDITOR NOTES
Link

Havish M Consulting ©
OFFICE RIBBONX EDITOR NOTES
Insert >
Sample XML >
Excel – A Custom
Tab

Havish M Consulting ©
OFFICE RIBBONX EDITOR NOTES

Havish M Consulting ©
PLUG-INS
PLUG-INS NOTES
Link

Havish M Consulting ©
WEBSITES
WEBSITES NOTES
Website
https://analystcave.com/
https://excelmacromastery.com/vba-articles/
https://www.thespreadsheetguru.com/catego
ry/vba/
https://analysistabs.com/vba-code/
https://wellsr.com/

Havish M Consulting ©
EXTRA CODES
Run macro only if file name and file path matches NOTES
Sub YourMacro()
Dim currentPath As String
Dim currentWorkbook As Workbook

' Get the current workbook


Set currentWorkbook = ThisWorkbook

' Get the current path


currentPath = Application.ThisWorkbook.Path

' Check if the current workbook is located within the current path
If InStr(1, currentWorkbook.FullName, currentPath, vbTextCompare) = 1
Then
' Your macro code here
MsgBox "Macro executed successfully within the current file and path!"
Else
MsgBox "Macro cannot run outside the current file or path!"
End If
End Sub
Havish M Consulting ©
Find Last Row NOTES
lastRow = Cells(Rows.Count, 1).End(xlUp).Row

=OFFSET(A1,COUNTA(A:A)-1,0)

Havish M Consulting ©
Ctrl + F NOTES
Sub FindValue()
Dim FindString As String
Dim Rng As Range

FindString = InputBox("Enter the value to find:")

Set Rng = ActiveSheet.Cells.Find(What:=FindString, LookIn:=xlValues,


_
LookAt:=xlPart, SearchOrder:=xlByRows,
SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)

If Not Rng Is Nothing Then


Application.Goto Rng, True 'Selects and makes the found cell active
Else
MsgBox "Value not found"
End If
End Sub
Havish M Consulting ©
Recording opening a file NOTES
Record opening
a file from the
backstage view

Double – click
opening file will
only activate
and not contain
the path

Havish M Consulting ©
YouTube Playlist NOTES
. Link

Havish M Consulting ©

You might also like