Slides - VBA
Slides - VBA
Havish M Consulting ©
WHAT IS VBA
Havish M Consulting ©
UNDERSTANDING 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.
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.
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.
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
Havish M Consulting ©
RUN MACROS WITH DEVELOPER > MACROS > RUN
Havish M Consulting ©
RUN MACROS FROM A SHAPE
Havish M Consulting ©
RUN MACROS FROM QAT
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
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
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.
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
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
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
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)
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
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
Havish M Consulting ©
FORMATTER NOTES
Link
Havish M Consulting ©
RECORD MACROS
RECORD MACROS NOTES
While recording
can toggle
between Absolute
and Relative
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
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
app = xw.App(visible=False) # Set visible to True if you want to see Excel operate
book = app.books.open(file_path)
sheet = book.sheets["Test"]
sheet.range("C5").formula = "=SUM(C6:C7)"
# Copy the formula from C5 to D5 through H5, adjusting the row references
formula = f"=SUM({column_letter}6:{column_letter}7)"
sheet.range(f"{column_letter}5").formula = formula
book.save()
book.close()
app.quit()
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
Havish M Consulting ©
TAKE VALUE NOTES
Sub ShowSelectedRangeInMessageBox()
Dim selectedRange As Range
Dim cell As Range
Dim message As String
' Loop through each cell in the selected range and concatenate their values
For Each cell In selectedRange
message = message & cell.Value & vbCrLf
Next cell
Havish M Consulting ©
TAKE VALUE NOTES
Get Info using ?
Havish M Consulting ©
WRITE VALUE TASK
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
Havish M Consulting ©
WRITE VALUE NOTES
={"Checked";"Pending";"Checked"}
Havish M Consulting ©
WRITE VALUE TASK
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
' 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
Havish M Consulting ©
WRITE VALUE NOTES
Excel is closed
Havish M Consulting ©
WRITE VALUE TASK
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
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
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()
Havish M Consulting ©
WRITE SERIAL NUMBERS - LOOP TASK
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
Havish M Consulting ©
FIND YTD TARGET - LOOP TASK
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
' 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
Havish M Consulting ©
FIND YTD TARGET - LOOP NOTES
Havish M Consulting ©
FIND YTD TARGET - LOOP NOTES
Havish M Consulting ©
CONDITIONAL STATEMENT - IF TASK
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
End Function
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
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)
End Function
Havish M Consulting ©
LAMBDA
Function UoM(myval As Double, unit As String)
End Function
Havish M Consulting ©
COMBINE FILES
COMBINE FILES NOTES
Link
Havish M Consulting ©
COMBINE FILES TASK
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
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
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
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 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 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 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
MsgBox rowCount
MsgBox columnCount
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
' 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
Double – click
opening file will
only activate
and not contain
the path
Havish M Consulting ©
YouTube Playlist NOTES
. Link
Havish M Consulting ©