VBA Detailed Guide
VBA Detailed Guide
B a s ic C o d e & F o r m u la s
B a s ic To p ic s
A d v a n c e d To p ic s
A d va n ce d C o n ce p ts
W e b S c r a p in g
Basic Explanation
1. What is Option Explicit?
2. Procedures
3. Functions
4. Dim(Define in Memory)
5. Class
6. Object
7. Set and New
8. Array
9. API
10. VBS
11. INSTR
12. Loop and Types of Loops
13. Types of Error
14. What is On Error and Types of On Error
15. Debug.Print
16. Immediate Window
17. Breakpoint
18. Watch Window
19. Immediate Window vs. Watch Window
20. Call Statement
21. DoEvents
22. With...End With Statement
23. Exit Statement
24. Select Case Statement
25. InputBox and MsgBox Functions
26. CreateObject and GetObject Functions
27. String Functions (Left, Right, Mid, Len, InStr)
28. Syntax
29. Variable
30. Range
31. Location
Basic Code & Formulas Basic Topics
1. Auto Fit Columns
2. Auto Fit Rows
3. Formatting
Coloring
Font
Interior
1. LOOKUP Bold Font
2. VLOOKUP LineStyle
3. HLOOKUP 4. Apply and Remove Text Wrap
4. AND 5. Merge and UnMerge Cell
5. OR 6. Remove Duplicate
6. COUNTIF 7. Sorting (Ascending, Descending)
7. COUNTIFS 8. Text To Column
8. COUNT 9. Types Of Error
9. COUNTA Compiler error
10. SUMIF Runtime error
11. SUMIFS Syntax error
12. IF Logical error
13. Nested IF
14. IFERROR
15. ISERROR
16. ISBLANK
17. INDEX
18. MATCH
19. INDEX & MATCH
20. RIGHT
21. LEFT
22. MID
23. SEARCH
24. SUBSTITUTE
25. CONCATENATE
26. TEXT
27. VALUE
28. CLEAR
29. CHAR
30. ABS
31. LEN
32. CHOOSE
1. VLOOKUP with IF
2. RIGHT with LEFT and LEN
3. CONCATENATE with IF and ISERROR
4. INDEX & MATCH with IFERROR
5. SUMIF with AND
6. COUNTIF with OR
Advanced Topics Advanced Concepts
1. Auto filter 1. Create Folder with FSO
Apply Autofilter 1. Delete Folder
Remove Autofilter 2. Folder Copy
2. Sheets 3. Folder Exist
Add 4. If Not Exist Then Create
Delete 5. TextFile Create
Copy 6. FSO TextFile Delete
Move 7. TextFile Open
Save As PDF 2. Functions
Insert Multiple Sheets Operators with functions
Protect all Worksheets FSO with functions
UnProtect Worksheet
Delete_Blank_Sheet 3. Others
3. IF Condition 1. Pivot Table
IF…EndIF 2. Pivot Charts
IF…Else…EndIF 3. Charts
Nested if 4. Sparklines
4. Loops 5. Slicer
For Next 6. Conditional Formatting
For Each Next 7. VBS
Do While 8. User Forms
Do Until 9. Class module
5. Error Handling 10. Protect Sheet
On error goto resume next 11. Protect Workbook
On error goto label 4. Consolidation
On error goto 0 Worksheet To Worksheet
On error goto -1 Worksheet to Another Workbook/Worksheet
goto jump Workbook To Workbook
Web Scraping
Data extraction 1. Data Extraction
Table reading 2. Table Reading
Alert 3. Handling Alerts
Frames 4. Handling Frames
Windows 5. Handling Windows
Dropdowns 6. Handling Dropdowns
Inputbox 7. Handling Input Boxes
File downloading (Excel, PDF) 8. File Downloading (Excel, PDF)
Screenshot 9. Taking Screenshots
Convert txt to Excel 10. Converting Text to Excel
Convert PDF to Excel 11. Converting PDF to Excel
Convert Word to Excel 12. Converting Word to Excel
API 13. Using APIs
VBS 14. Using VBS (VBScript)
Wait until element present 15. Waiting Until an Element is Present
1. Basic Explanation 2. Basic Code & Fo
1. What is Option Explicit? 1. Declaring Workbook
Worksheet
2. Procedures
2. Finding Last Row and
Column
3. Functions
3. Storing Cell Value i
4. Dim(Define in Memory) Variable
5. Class 4. Working with Rang
6. Object 5. Assigning Values to C
7. Set and New
1. LOOKUP
8. Array
2. VLOOKUP
9. API
3. HLOOKUP
10. VBS
4. AND
11. INSTR
5. OR
12. Loop and Types of
Loops
6. COUNTIF
13. Types of Error
7. COUNTIFS
14. What is On Error
and Types of On Error 8. COUNT
15. Debug.Print
9. COUNTA
16. Immediate Window
10. SUMIF
17. Breakpoint
11. SUMIFS
18. Watch Window
12. IF
19. Immediate Window
vs. Watch Window 13. Nested IF
20. Call Statement 14. IFERROR
21. DoEvents
15. ISERROR
22. With...End With
Statement 16. ISBLANK
28. CLEAR
29. CHAR
30. ABS
31. LEN
32. CHOOSE
1. VLOOKUP with IF
3. CONCATENATE with I
ISERROR
6. COUNTIF with OR
4. INDEX & MATCH w
IFERROR
6. COUNTIF with OR
sic Code & Formulas 3. Basic Topics
1. Declaring Workbook and
Worksheet 1. Auto Fit Columns
4. AND LineStyle
16. ISBLANK
17. INDEX
14. IFERROR Syntax error
16. ISBLANK
17. INDEX
18. MATCH
20. RIGHT
21. LEFT
22. MID
23. SEARCH
24. SUBSTITUTE
25. CONCATENATE
26. TEXT
27. VALUE
28. CLEAR
29. CHAR
30. ABS
31. LEN
32. CHOOSE
1. VLOOKUP with IF
6. COUNTIF with OR
4. INDEX & MATCH with
IFERROR
6. COUNTIF with OR
4. Advanced Topics 5.
1. Auto filter
Apply Autofilter
Remove Autofilter
2. Sheets
Add
Delete
Copy
Move
Wrap
Save As PDF
ell
Insert Multiple Sheets
UnProtect Worksheet
Delete_Blank_Sheet
3. IF Condition
IF…EndIF
IF…Else…EndIF
Nested if
4. Loops
For Next
Nested if
4. Loops
For Next
Do While
Do Until
5. Error Handling
On error goto 0
On error goto -1
goto jump
5. Advanced Concepts 6. Web Sc
1. Create Folder with FSO 1. Data Ex
2. Functions 9. Taking Sc
4. Sparklines Logical
5. Slicer
6. Conditional Formatting
7. VBS
5. Slicer
6. Conditional Formatting
7. VBS
8. User Forms
9. Class module
4. Consolidation
Worksheet To Worksheet
Worksheet to Another
Workbook/Worksheet
Workbook To Workbook
6. Web Scraping
1. Data Extraction
2. Table Reading
3. Handling Alerts
4. Handling Frames
5. Handling Windows
6. Handling Dropdowns
9. Taking Screenshots
Logical error
Web Scraping
Web scraping in VBA using Selenium can be a powerful tool for automating tasks that involve interac
Prerequisites
Before you begin, ensure you have the following:
1. Selenium Basic installed. You can download it from here.
2. ChromeDriver compatible with your Chrome browser version. You can download it from here.
1. Data Extraction
Data extraction involves retrieving specific information from a web page.
Example:
Let's extract the titles of articles from a news website.
Example Data:
Website: https://news.ycombinator.com/
Example Code:
Sub ExtractData()
Dim browser As New ChromeDriver
Dim elements As WebElements
Dim element As WebElement
Dim i As Integer
browser.Start "Chrome"
browser.Get "https://news.ycombinator.com/"
For i = 1 To elements.Count
Set element = elements.Item(i - 1)
Debug.Print element.Text
Next i
browser.Quit
End Sub
Steps:
1. Start the Chrome browser.
2. Navigate to the website.
3. Find elements using the CSS selector.
4. Loop through the elements and print their text.
Result: This code will print the titles of the articles on the Hacker News front page in the Immediate
Explanation:
FindElementsByCss("a.storylink"): This finds all anchor tags with the class storylink.
element.Text: This retrieves the text content of each element.
2. Table Reading
Reading data from a table on a webpage involves finding the table element and iterating through its
Example:
Read the data from a table on a sample website.
Example Data:
Website: https://www.w3schools.com/html/html_tables.asp
Example Code:
Sub ReadTable()
Dim browser As New ChromeDriver
Dim table As WebElement
Dim rows As WebElements
Dim cells As WebElements
Dim row As WebElement
Dim cell As WebElement
Dim i As Integer, j As Integer
browser.Start "Chrome"
browser.Get "https://www.w3schools.com/html/html_tables.asp"
Set table = browser.FindElementById("customers")
Set rows = table.FindElementsByTag("tr")
For i = 2 To rows.Count
Set row = rows.Item(i - 1)
Set cells = row.FindElementsByTag("td")
For j = 1 To cells.Count
Set cell = cells.Item(j - 1)
Debug.Print cell.Text
Next j
Next i
browser.Quit
End Sub
Steps:
1. Start the Chrome browser.
2. Navigate to the website.
3. Find the table element by its ID.
4. Loop through the rows and cells, printing the cell text.
Result: This code will print the contents of each cell in the "customers" table on the W3Schools HTM
Explanation:
FindElementById("customers"): Finds the table element by its ID.
FindElementsByTag("tr"): Finds all the row elements within the table.
FindElementsByTag("td"): Finds all the cell elements within a row.
3. Handling Alerts
Handling alerts involves switching the focus to the alert and accepting or dismissing it.
Example Data:
Website: A website that triggers a JavaScript alert (for demonstration purposes).
Example Code:
Sub HandleAlert()
Dim browser As New ChromeDriver
browser.Start "Chrome"
browser.Get "http://example.com/alert"
If browser.IsAlertPresent Then
browser.SwitchToAlert.Accept
End If
browser.Quit
End Sub
Steps:
1. Start the Chrome browser.
2. Navigate to the website.
3. Check if an alert is present.
4. Accept the alert.
Result: The code will accept any alert that appears on the page.
Explanation:
IsAlertPresent: Checks if an alert is present.
SwitchToAlert.Accept: Switches to the alert and accepts it.
4. Handling Frames
Handling frames involves switching the focus to a specific frame before interacting with elements ins
Example Data:
Website: https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_iframe
Example Code:
Sub HandleFrame()
Dim browser As New ChromeDriver
browser.Start "Chrome"
browser.Get "https://www.w3schools.com/tags/tryit.asp?filename=t
browser.SwitchToFrame ("iframeResult")
browser.SwitchToFrame (0)
Debug.Print browser.FindElementByTag("h1").Text
browser.Quit
End Sub
Steps:
1. Start the Chrome browser.
2. Navigate to the website.
3. Switch to the frame.
4. Interact with elements inside the frame.
Result: The code will print the text of the h1 tag inside the iframe.
Explanation:
SwitchToFrame("iframeResult"): Switches to the frame with the ID iframeResult.
SwitchToFrame(0): Switches to the first frame within the current frame.
5. Handling Windows
Handling multiple windows involves switching the focus between different browser windows or tabs
Example Data:
Website: A website that opens a new window (for demonstration purposes).
Example Code:
Sub HandleWindow()
Dim browser As New ChromeDriver
Dim handles As Collection
browser.Start "Chrome"
browser.Get "http://example.com"
browser.FindElementByLinkText("Open new window").Click
browser.Quit
End Sub
Steps:
1. Start the Chrome browser.
2. Navigate to the website.
3. Click a link that opens a new window.
4. Switch to the new window and print its title.
Result: The code will print the title of the newly opened window.
Explanation:
WindowHandles: Retrieves a collection of all open window handles.
SwitchToWindow(handles.Item(2)): Switches to the second window.
6. Handling Dropdowns
Handling dropdowns involves selecting an option from a dropdown list.
Example Data:
Website: https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select
Example Code:
Sub HandleDropdown()
Dim browser As New ChromeDriver
browser.Start "Chrome"
browser.Get "https://www.w3schools.com/tags/tryit.asp?filename=t
browser.SwitchToFrame ("iframeResult")
browser.FindElementByTag("select").AsSelect.SelectByValue "saab"
browser.Quit
End Sub
Steps:
1. Start the Chrome browser.
2. Navigate to the website.
3. Switch to the frame.
4. Select an option from the dropdown.
Result: The code will select the "Saab" option from the dropdown list.
Explanation:
AsSelect.SelectByValue("saab"): Selects the option with the value saab.
Example Code:
Sub DownloadFile()
Dim browser As New ChromeDriver
Dim downloadPath As String
browser.AddArgument "--headless"
browser.AddArgument "--disable-gpu"
browser.AddArgument "--window-size=1920,1200"
browser.AddArgument "--disable-extensions"
browser.AddArgument "--proxy-server='direct://'"
browser.AddArgument "--proxy-bypass-list=*"
browser.AddArgument "--start-maximized"
browser.AddArgument "--disable-dev-shm-usage"
browser.AddArgument "--no-sandbox"
browser.AddPreference "download.default_directory", downloadPath
browser.AddPreference "download.prompt_for_download", False
browser.AddPreference "download.directory_upgrade", True
browser.AddPreference "plugins.always_open_pdf_externally", True
browser.Start "Chrome"
browser.Get "http://example.com/download"
browser.FindElementByLinkText("Download file").Click
browser.Quit
End Sub
Steps:
1. Start the Chrome browser with download preferences.
2. Navigate to the website.
3. Click the link to download the file.
9. Taking Screenshots
Taking screenshots involves capturing the current view of the browser window.
Example Data:
Website: https://www.example.com
Example Code:
Sub TakeScreenshot()
Dim browser As New ChromeDriver
Dim screenshotPath As String
screenshotPath = "C:\Screenshots\screenshot.png" ' Change this to
browser.Start "Chrome"
browser.Get "https://www.example.com"
browser.GetScreenshot.SaveAs screenshotPath
browser.Quit
End Sub
Steps:
1. Start the Chrome browser.
2. Navigate to the website.
3. Take a screenshot and save it to the specified path.
Result: The screenshot will be saved to the specified directory.
Explanation:
GetScreenshot.SaveAs screenshotPath: Takes a screenshot and saves it to the specified path.
text = wordDoc.Content.Text
wordDoc.Close
wordApp.Quit
i=1
For Each line In Split(text, vbCrLf)
Cells(i, 1).Value = line
i=i+1
Next line
End Sub
Steps:
1. Open the Word document.
2. Read the text data.
3. Write the text data to an Excel worksheet.
Result: The Word data will be written to the worksheet, one line per cell.
Explanation:
wordDoc.Content.Text: Reads the text content of the Word document.
Split(text, vbCrLf): Splits the text into lines.
Steps:
1. Specify the VBScript file path.
2. Run the VBScript file using cscript.exe.
Result: The VBScript code will be executed.
Explanation:
Shell "cscript.exe " & vbsFile: Runs the VBScript file using the cscript.exe command.
storylink")
class storylink.
t and iterating through its rows and cells.
html_tables.asp"
html_iframe
tryit.asp?filename=tryhtml_iframe"
rameResult.
ndow").Click
html_select
tryit.asp?filename=tryhtml_select"
SelectByValue "saab"
html_forms.asp"
dKeys "John"
Keys "Doe"
ctory", downloadPath
download", False
grade", True
df_externally", True
necessary
el worksheet.
it to an Excel worksheet.
uch as PDFBox or iTextSharp, which are not native to VBA.
n element in a loop.
econd timeout
iv.dynamic-content")
between checks.
Basic Explanation
1. What is Option Explicit?
Explanation:
Option Explicit forces explicit declaration of all variables, reducing errors from typos and en
Example:
Option Explicit
Sub Example()
Dim i As Integer
i = 10
MsgBox i
End Sub
Explanation: The Option Explicit statement ensures that the variable i is declared before u
compile-time error.
2. Procedures
Explanation:
i) When we write a macro in vba that is called Procedure.
ii) Procedures are blocks of code that perform specific tasks. There are two types: Sub (Sub
Sub: Does not return a value.
Function: Returns a value.
Example:
Sub ShowMessage()
MsgBox "Hello, World!"
End Sub
3. Functions
Explanation:
i) Function is group of variable which we can use anywhere in a program.
ii)Function is group of reusable code we can use anywhere in a program
iii)Functions perform calculations and return values. They can be called within ot
Example:
Function SquareNumber(Number As Integer) As Integer
SquareNumber = Number * Number
End Function
Sub Example()
MsgBox SquareNumber(5) ' Displays 25
End Sub
Explanation: The SquareNumber function calculates the square of a number and returns i
displays the result.
4. Dim(Define in Memory)
Explanation:
i) Dim is used to declare variables and allocate storage space.
Example:
Sub DeclareVariables()
Dim i As Integer
Dim s As String
Dim d As Double
i = 10
s = "Hello"
d = 3.14
MsgBox i & " " & s & " " & d
End Sub
Explanation: Variables i, s, and d are declared with Dim and assigned values. The MsgBox
5. Class
Explanation:
i) Classes are blueprints for creating objects, encapsulating data (properties) and behavior (
ii) A Class describes the variables, Properties, Procedures and events of an Object.
Example:
' In a class module named "Car"
Private pColor As String
Explanation: The Car class has a property Color and a method Drive. The TestCar Sub de
setting its Color property, and calling the Drive method.
6. Object
Explanation:
i) Object is an instance of a class. Through the class we can access the class Properties, Me
ii) Objects represent elements like workbooks, worksheets, and ranges. Objects have prope
Example:
Sub UseObject()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
ws.Range("A1").Value = "Hello, World!"
End Sub
Explanation: ws is declared as a Worksheet object and set to the first sheet in the workbo
set to "Hello, World!".
8. Array
Explanation 1:-
Array is a group of variable and collection of variable
Array is like a mini storage box where we can store the value and data.
There are the five types of array:-
Static Array
Dynamic Array
Dimension
2 Dimension
multidimensional Arrays
Explanation 2:- Arrays store multiple values in a single variable. Arrays can be static (fixed s
Example:
Sub StaticArray()
Dim arr(1 To 5) As Integer
Dim i As Integer
For i = 1 To 5
arr(i) = i * 2
Next i
MsgBox arr(3) ' Displays 6
End Sub
Sub DynamicArray()
Dim arr() As Integer
Dim i As Integer
ReDim arr(1 To 5)
For i = 1 To 5
arr(i) = i * 2
Next i
MsgBox arr(3) ' Displays 6
End Sub
Explanation: StaticArray uses a fixed-size array, while DynamicArray uses a resizable arra
and display the value at the third position.
9. API
Explanation:
i) The Full form of API is "Application Programming interface" it is set of methods that direc
ii) API allow VBA to call functions from external libraries, such as the Windows API.
Example:
Sub UseAPI()
Dim tick As Long
tick = GetTickCount()
MsgBox tick
End Sub
Explanation: GetTickCount is a Windows API function that returns the number of milliseco
UseAPI Sub calls this function and displays the result.
10. VBS
Explanation:
VBScript (VBS) is a scripting language similar to VBA but used for different purposes, such a
applications.
Example:
' Save this as a .vbs file and run it
Dim message
message = "Hello from VBScript!"
MsgBox message
Explanation: This VBScript code displays a message box with the text "Hello from VBScript!
it to see the message.
11. INSTR
Explanation:
i) INSTR return the position of string value in numeric value
ii) INSTR is a function which search the position of the character from a string
iii) INSTR function returns the position of the first occurrence of a substring within another
Example:
Sub FindSubstring()
Dim pos As Integer
pos = InStr(1, "Hello, World!", "World")
MsgBox pos ' Displays 8
End Sub
Explanation: InStr searches for "World" in "Hello, World!" starting from position 1. It return
For Each loop is used to execute a statements or group of statements for each elements in
' For Each...Next loop
Sub ForEachLoop()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Sheets
MsgBox ws.Name
Next ws
End Sub
Explanation: Each example demonstrates a different type of loop, displaying values from 1
Sub ErrorHandler()
On Error GoTo ErrorHandler
Dim i As Integer
i = 1 / 0 ' Division by zero error
MsgBox "After error" ' This line is skipped
Exit Sub
ErrorHandler:
MsgBox "Error occurred!"
Resume Next ' Resume next line after error
End Sub
Explanation: The On Error GoTo ErrorHandler directs the code to ErrorHandler upon en
continues execution after handling the error.
15. Debug.Print
Explanation: Debug.Print outputs messages to the Immediate window during code executi
Example:
Sub DebugPrintExample()
Dim i As Integer
For i = 1 To 5
Debug.Print "Iteration: " & i
Next i
End Sub
Explanation: Debug.Print prints each iteration of the loop to the Immediate window.
17. Breakpoint
Explanation: A breakpoint pauses code execution at a specified line for inspection during d
Example:
Click on the left margin of a line in the VBA editor to set or remove a breakpoint.
Sub ShowMessage()
MsgBox "Hello, World!"
End Sub
Explanation: CallExample calls the ShowMessage subroutine using the Call statement.
21. DoEvents
Explanation: DoEvents yields execution to other applications or processes during lengthy
Example:
Sub DoEventsExample()
Dim i As Integer
For i = 1 To 10000
Cells(1, 1).Value = i
DoEvents ' Allows Excel to process other events
Next i
End Sub
Explanation: DoEvents ensures Excel processes other events while the loop updates cell v
Explanation: Exit For stops the loop when i equals 5 in the ExitExample procedure.
Explanation: InputBox prompts for a name, and MsgBox greets the user.
29. Variable
Explanation: A variable is a named storage location in memory used to hold data during pro
declared before they can be used, specifying their data type.
Example:
Sub ExampleVariable()
Dim age As Integer
age = 30
MsgBox "Age is " & age
End Sub
Explanation:
Dim age As Integer: Declares a variable age as an integer.
age = 30: Assigns the value 30 to age.
MsgBox "Age is " & age: Displays a message box with the value of age.
30. Range
Explanation: In Excel VBA, a range refers to a collection of cells within a worksheet. It can b
entire row or column.
Example:
Sub ExampleRange()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
Dim myRange As Range
Set myRange = ws.Range("A1:B5")
myRange.Value = "Hello"
End Sub
Explanation:
Dim ws As Worksheet: Declares a worksheet variable ws.
Set ws = ThisWorkbook.Sheets("Sheet1"): Sets ws to refer to "Sheet1" in the curren
Dim myRange As Range: Declares a range variable myRange.
Set myRange = ws.Range("A1:B5"): Sets myRange to cover cells A1 to B5 on "Sheet
myRange.Value = "Hello": Sets the value of all cells in myRange to "Hello".
31. Location
Explanation: Location in programming generally refers to where something is stored or pos
Physical Location: Such as the address of a cell in Excel (Range("A1")).
Memory Location: Where variables or objects are stored in computer memory.
Example:
Sub ExampleLocation()
Dim cellValue As String
cellValue = Range("A1").Value
MsgBox "Value in A1 is: " & cellValue
End Sub
Explanation:
Dim cellValue As String: Declares a variable cellValue to store string data.
cellValue = Range("A1").Value: Assigns the value of cell A1 to cellValue.
MsgBox "Value in A1 is: " & cellValue: Displays a message box with the value of cellV
xplanation
ariable i is declared before use. If i were not declared, VBA would raise a
Integer) As Integer
er) As Integer
e of a number and returns it. The Example Sub calls this function and
ce of an object.
b "kernel32" () As Long
from a string
a substring within another string. It is case-sensitive.
ement found e.g we use If condition but we forgot to add End IF.
ect result
an error occurs.
ule it will skip the error line and continues with second line.
ror handler which Shows error messages each time an error occurs.
he Immediate window.
move a breakpoint.
unction in VBA.
sage subroutine
ther events
hile the loop updates cell values.
n i equals 5
Example procedure.
ox accordingly.
plication")
de of a string.
t side of a string.
tarting at a specified position.
g within another.
tions of symbols and words that are valid in a programming
eter to understand and execute code correctly.
he value of x.
alue of age.
mputer memory.
Basic Code
1. Declaring Workbook and Worksheet:-
Explanation: Declaring workbook and worksheet allows us to refer to specific Excel files and sheets in
Data: Use ThisWorkbook to refer to the workbook containing the VBA code, and use Worksheets to
Example:
Dim wb As Workbook
Set wb = ThisWorkbook ' Refers to the current workbook
Dim ws As Worksheet
Set ws = wb.Worksheets("Sheet1") ' Refers to a specific worksheet na
Example Code: This code sets the current workbook to the variable wb and the worksheet named "S
Steps:
Dim wb As Workbook: Declare a variable wb as type Workbook.
Set wb = ThisWorkbook: Assign the current workbook to the variable wb.
Dim ws As Worksheet: Declare a variable ws as type Worksheet.
Set ws = wb.Worksheets("Sheet1"): Assign the worksheet named "Sheet1" to the variab
Example Code: This code sets the variable lastRow to the last used row number in column A and last
worksheet ws.
Steps:
Dim lastRow As Long: Declare a variable lastRow to store the last row number.
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row: Set lastRow to the last used row
Dim lastColumn As Long: Declare a variable lastColumn to store the last column numbe
lastColumn = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column: Set lastColumn to th
Example:
Example Code: This code stores the value of cell A1 in the variable cellValue.
Steps:
Dim cellValue As Variant: Declare a variable cellValue to store the cell's value.
cellValue = ws.Cells(1, 1).Value: Assign the value of cell A1 to the variable cellValue.
Example:
Example Code: This code sets the variable rng to represent the range from A1 to B10 in worksheet w
Steps:
Dim rng As Range: Declare a variable rng to represent a range of cells.
Set rng = ws.Range("A1:B10"): Assign the range A1
in worksheet ws to the variable rng.
Example:
Example Code: This code puts the value "Hello" into cell A1 of worksheet ws and sets the value "Sam
Steps:
ws.Cells(1, 1).Value = "Hello": Assign the value "Hello" to cell A1.
Dim rng As Range: Declare a variable rng to represent a range of cells.
Set rng = ws.Range("A1:B10"): Assign the range A1 in worksheet ws to the variable rng
rng.Value = "Sample": Assign the value "Sample" to the entire range A1
Formulas
Notes:-
1. LOOKUP
Explanation: The LOOKUP function searches for a value in a range and returns a corresponding valu
Data: Assume we have the following data in Sheet1:
A B
1 Apple
2 Banana
3 Cherry
2. VLOOKUP
Explanation: The VLOOKUP function searches for a value in the first column of a table and returns a
Example Code:
Sub UseVLookup()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
3. HLOOKUP
Explanation: The HLOOKUP function searches for a value in the first row of a table and returns a val
Data: Assume we have the following data in Sheet1:
A 1 2 3
B Apple Banana Cherry
We want to find the fruit name corresponding to the number 2.
Example Code:
Sub UseHLookup()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
4. AND
Explanation: The AND function checks if all arguments are TRUE, and returns TRUE if they are, other
Data: Assume we have the following data in Sheet1:
A B
5 10
15 20
25 30
We want to check if the value in cell A1 is greater than 4 and less than 6.
Example Code:
Sub UseAnd()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
6. COUNTIF
Explanation: The COUNTIF function counts the number of cells within a range that meet a single con
Data: Assume we have the following data in Sheet1:
A
Apple
Banana
Cherry
Apple
We want to count the number of cells containing "Apple".
Example Code:
Sub UseCountIf()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
7. COUNTIFS
Explanation: The COUNTIFS function counts the number of cells that meet multiple criteria.
Data: Assume we have the following data in Sheet1:
A B
Apple Red
Banana Yellow
Cherry Red
Apple Green
8. COUNT
Explanation: The COUNT function counts the number of cells that contain numbers.
A
1
2
Apple
4
Example Code:
Sub UseCount()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
9. COUNTA
Explanation: The COUNTA function counts the number of non-empty cells.
Data: Assume we have the same data in Sheet1.
Example Code:
Sub UseCountA()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
' Insert COUNTA formula in cell B3 using R1C1 notation
ws.Range("B3").FormulaR1C1 = "=COUNTA(R1C1:R4C1)"
End Sub
Result: Cell B3 in Sheet1 will show 4.
10. SUMIF
Explanation: The SUMIF function adds the cells specified by a given condition or criteria.
Data: Assume we have the following data in Sheet1:
A B
Apple 10
Banana 20
Cherry 30
Apple 40
We want to sum the values in column B for cells in column A that contain "Apple".
Example Code:
Sub UseSumIf()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
11. SUMIFS
Explanation: The SUMIFS function adds the cells specified by multiple conditions or criteria.
Data: Assume we have the same data in Sheet1.
Example Code:
Sub UseSumIfs()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
12. IF
Explanation: The IF function checks whether a condition is met, and returns one value if TRUE, and a
Data: Assume we have the following data in Sheet1:
A
5
10
15
20
13. Nested IF
Explanation: Nested IF functions allow multiple conditions to be evaluated in a single formula.
Data: Assume we have the following data in Sheet1:
A
5
10
15
20
We want to categorize the values in column A as "Low", "Medium", or "High".
Example Code:
Sub UseNestedIf()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
14. IFERROR
Explanation: The IFERROR function returns a value if an expression evaluates to an error; otherwise
Data: Assume we have the following data in Sheet1:
A B
10 2
10 0
10 5
We want to divide column A by column B and handle any division errors.
Example Code:
Sub UseIfError()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
Result: Cell C5 in Sheet1 will show "5" and cell C6 will show "Error".
15. ISERROR
Explanation: The ISERROR function returns TRUE if the expression is an error, and FALSE otherwise.
Data: Assume we have the same data in Sheet1.
Example Code:
Sub UseIsError()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
Result: Cell D5 in Sheet1 will show FALSE and cell D6 will show TRUE.
16. ISBLANK
Explanation: The ISBLANK function returns TRUE if the cell is empty, and FALSE otherwise.
Data: Assume we have the following data in Sheet1:
A
10
We want to check if cell A1 is blank.
Example Code:
Sub UseIsBlank()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
17. INDEX
Explanation: The INDEX function returns the value of an element in a table or array, selected by the
Data: Assume we have the following data in Sheet1:
A B
Apple Red
Banana Yellow
Cherry Red
We want to find the value in the second row and second column.
Example Code:
Sub UseIndex()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
18. MATCH
Explanation: The MATCH function searches for a value in an array and returns the relative position o
Data: Assume we have the following data in Sheet1:
A
Apple
Banana
Cherry
We want to find the position of "Banana" in column A.
Example Code:
Sub UseMatch()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
' Insert INDEX & MATCH formula in cell C7 using R1C1 notation
ws.Range("C7").FormulaR1C1 = "=INDEX(R1C1:R3C2, MATCH(""Bana
End Sub
20. RIGHT
Explanation: The RIGHT function returns the last character or characters in a text string, based on th
Data: Assume we have the following data in Sheet1:
A
Apple
Banana
Cherry
We want to get the last 2 characters from the text in cell A1.
Example Code:
Sub UseRight()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
21. LEFT
Explanation: The LEFT function returns the first character or characters in a text string, based on the
Data: Assume we have the same data in Sheet1.
Example Code:
Sub UseLeft()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
22. MID
Explanation: The MID function returns a specific number of characters from a text string, starting at
Data: Assume we have the same data in Sheet1.
Example Code:
Sub UseMid()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
24. SUBSTITUTE
Explanation: The SUBSTITUTE function replaces existing text with new text in a text string.
Example Code:
Sub UseSubstitute()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
25. CONCATENATE
Explanation: The CONCATENATE function joins two or more text strings into one string.
Data: Assume we have the following data in Sheet1:
A B
Apple Pie
26. TEXT
Explanation: The TEXT function converts a value to text in a specified number format.
Data: Assume we have the following data in Sheet1:
A
0.5
We want to format the number as a percentage.
Example Code:
Sub UseText()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
27. VALUE
Explanation: The VALUE function converts a text string that represents a number to a number.
Data: Assume we have the following data in Sheet1:
A
123
We want to convert the text "123" to the number 123.
Example Code:
Sub UseValue()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
28. CLEAR
Explanation: The CLEAR function does not exist as a worksheet function, but you can clear cell cont
Example Code:
Sub UseClear()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
29. CHAR
Explanation: The CHAR function returns the character specified by a number.
Data: Assume we want to get the character for the ASCII code 65.
Example Code:
Sub UseChar()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
30. ABS
Explanation: The ABS function returns the absolute value of a number.
Data: Assume we have the following data in Sheet1:
A
-5
We want to get the absolute value of the number.
Example Code:
Sub UseAbs()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
31. LEN
Explanation: The LEN function returns the number of characters in a text string.
Data: Assume we have the following data in Sheet1:
A
Apple
We want to get the length of the text in cell A1.
Example Code:
Sub UseLen()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
' Insert LEN formula in cell B17 using R1C1 notation
ws.Range("B17").FormulaR1C1 = "=LEN(R1C1)"
End Sub
Result: Cell B17 in Sheet1 will show 5.
32. CHOOSE
Explanation: The CHOOSE function returns a value from a list of values based on an index number.
Data: Assume we have the following data in Sheet1:
A
2
We want to return the second value from the list "Apple", "Banana", "Cherry".
Example Code:
Sub UseChoose()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
Multiple Formul
1. VLOOKUP with IF
Explanation: Using VLOOKUP with IF to return different results based on a condition.
We want to use VLOOKUP to find the value in column B based on column A and use IF to modify the
Example Code:
Sub VlookupWithIf()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
' Insert VLOOKUP with IF formula in cell C19 using R1C1 notation
ws.Range("C19").FormulaR1C1 = "=IF(VLOOKUP(2, R1C1:R3C2, 2, FA
End Sub
part1 = "Hello"
part2 = "World"
lookupValue = "Banana"
' Find the row number of the lookup value in the first column
matchRow = -1
For i = 1 To ws.Range("A1:A3").Cells.Count
If ws.Cells(i, 1).Value = lookupValue Then
matchRow = i
Exit For
End If
Next i
Result: If "Banana" is found in the range A1, the corresponding value from column B (row 2, which is
displayed.
6. COUNTIF with OR
Explanation: Use COUNTIF to count cells based on a single condition, and combine with OR for multi
Data:
*Range:
A
1 Apple
2 Banana
3 Apple
4 Cherry
Criteria1: "Apple"
Criteria2: "Banana"
Example Code:
Dim count1 As Long
Dim count2 As Long
Result:
Count1: 2 (number of times "Apple" appears)
Count2: 1 (number of times "Banana" appears)
Message: "At least one condition is met. Count1: 2, Count2: 1"
Code & Formulas
Notes:-
1. Do not make any type of edit or modification to this file. Follow the
steps provided below exactly as they are given.
2. First, create a new folder named "VBA Practice Files
3. Inside the "VBA Practice Files" folder, create two new folders named
"Input"
4. Now, and "Output
within the "VBA Practice Files" folder, create a new Excel file
named "VBA Learning Journey". Include your name and employee ID in
the format "VBA Learning Journey_Zubair Mistry_CI14602", and save it
in xlsm format so that VBA coding can be done
asic Code
xlToLeft).Column
mber in column A and lastColumn to the last used column in row 1 of the
row number.
ow to the last used row in column A of worksheet ws.
he last column number.
n: Set lastColumn to the last used column in row 1 of worksheet ws.
able cellValue.
namically in Excel.
A1 to B10
A1 to B10
Formulas
1C1:R3C1, R1C2:R3C2)"
n of a table and returns a value in the same row from another column.
R1C1:R3C2, 2, FALSE)"
f a table and returns a value in the same column from another row.
R1C2:R2C4, 2, FALSE)"
, R1C1<6)"
returns TRUE if any argument is TRUE, otherwise, it returns FALSE.
R1C1=15)"
1:R4C1, ""Apple"")"
multiple criteria.
C1:R4C1, ""Apple"", R1C2:R4C2, ""Red"")"
on or criteria.
ditions or criteria.
in a single formula.
ALSE otherwise.
ok up values in a table.
R1C1 notation
R3C2, MATCH(""Banana"", R1C1:R3C1, 0), 2)"
a text string, based on the number of characters specified.
"", R1C1)"
t in a text string.
1C1 notation
(R1C1, ""p"", ""b"")"
""0.0%"")"
umber to a number.
ut you can clear cell contents using VBA.
sed on an index number.
iple Formulas
ISERROR to conditionally handle errors. This combination is useful for constructing strings
with a space
lumn numbers and MATCH to find the row or column number. Use IFERROR to handle errors gracefully.
rst column
avoid errors
column B (row 2, which is 20) is displayed. If not, a message "Value not found" is
Result: The columns A, B, and C will adjust their widths to fit the content.
Result: The rows 1 to 3 will adjust their heights to fit the content.
3. Formatting
Explanation: Apply various formatting styles such as coloring, font, interior, bold font, and line style.
Coloring:-
Data: Sample data for applying coloring.
A B C
Departme
Name Location
nt
John Doe IT New York
Jane
HR London
Smith
Michael Finance Sydney
Example Code:
Sub ApplyColoring()
' Apply background color to range A1:C1
Range("A1:C1").Interior.Color = RGB(255, 255, 0) ' Yellow color
End Sub
Sub RemoveTextWrap()
' Remove text wrap from range A1:C1
Range("A1:C1").WrapText = False
End Sub
Sub UnmergeCells()
' Unmerge cells in range A1:C1
Range("A1:C1").UnMerge
End Sub
6. Remove Duplicate
Explanation: Remove duplicate values from a range.
Data: Sample data with duplicates.
A B C
Departme
Name Location
nt
John Doe IT New York
Jane
HR London
Smith
John Doe IT New York
Michael Finance Sydney
Example Code:
Sub RemoveDuplicates()
' Remove duplicates from range A1:C4
Range("A1:C4").RemoveDuplicates Columns:=Array(1, 2, 3), Header:=xl
End Sub
Sub SortDescending()
' Sort range A1:C3 in descending order by Name
Range("A1:C3").Sort Key1:=Range("A1"), Order1:=xlDescending, Heade
8. Text To Column
Explanation: Split the text in a single column into multiple columns based on a delimiter.
Data: Sample data for text to column.
A
Name,De
partment,
Location
John
Doe,IT,Ne
w York
Jane
Smith,HR,
London
Michael,Fi
nance,Syd
ney
Example Code:
Sub TextToColumn()
' Split the text in column A into multiple columns using a comma as the
Range("A1:A4").TextToColumns Destination:=Range("A1"), DataType:=x
ConsecutiveDelimiter:=False,_ Tab:=False, Semicolon:=False, Comma:=Tru
End Sub
Result: The text in column A will be split into multiple columns based on the comma delimiter.
9. Types Of Error
Compiler Error:-
Explanation: Compiler errors occur when the code does not comply with the syntax rules of the VBA lang
Example Code:
Sub CompilerErrorExample()
' This code will cause a compiler error due to incorrect syntax
Dim x As Integer
x = 10
' Missing End Sub statement will cause a compiler error
Result: A compiler error will be displayed indicating that there is a syntax error.
Runtime Error:-
Explanation: Runtime errors occur during the execution of the code, usually due to invalid operations or
Example Code:
Sub RuntimeErrorExample()
' This code will cause a runtime error due to division by zero
Dim x As Integer
Dim y As Integer
x = 10
y=0
MsgBox x / y
End Sub
Result: A runtime error will be displayed indicating that division by zero is not possible.
Syntax Error:-
Explanation: Syntax errors occur when the code is written with incorrect syntax.
Example Code:
Sub SyntaxErrorExample()
' This code will cause a syntax error due to incorrect syntax
Dim x As Integer
x = "Hello" ' Assigning a string to an integer variable will cause a syntax
End Sub
Result: A syntax error will be displayed indicating that there is an issue with the code.
Logical Error:-
Explanation: Logical errors occur when the code runs without errors but produces incorrect results due t
Example Code:
Sub LogicalErrorExample()
' This code will cause a logical error due to incorrect logic
Dim x As Integer
Dim y As Integer
x = 10
y = 20
MsgBox "The sum of x and y is " & x - y ' Incorrect logic for addition
End Sub
Result: The message box will display an incorrect result due to the logical error in the code.
sic Topics
the content.
, bold font, and line style.
1:=xlDescending, Header:=xlYes
on a delimiter.
s using a comma as the delimiter
ange("A1"), DataType:=xlDelimited, TextQualifier:=xlDoubleQuote,
olon:=False, Comma:=True, Space:=False, Other:=False
he comma delimiter.
correct syntax
ision by zero
not possible.
rrect syntax
rrect logic
Sub ApplyAutoFilter()
' Select the range where you want to apply the filter
Range("A1:C10").AutoFilter
End Sub
Remove Autofilter:-
Explanation: Removing an autofilter clears all the applied filters from a range.
Example Code:
Sub RemoveAutoFilter()
' Check if there is an autofilter applied
If ActiveSheet.AutoFilterMode Then
ActiveSheet.AutoFilterMode = False
End If
End Sub
Steps and Result: Same as above. Running this macro will remove any autofilter applied on the active sh
2. Sheets
Add:-
Explanation: Adding a new worksheet to the workbook.
Example Code:
Sub AddSheet()
Sheets.Add After:=Sheets(Sheets.Count)
End Sub
Steps and Result: Running this macro will add a new worksheet at the end of the existing worksheets.
Delete:-
Steps and Result: Replace "SheetName" with the actual sheet name you want to delete. This will delete
message.
Copy:-
Explanation: Copying a worksheet within the same workbook.
Example Code:
Sub CopySheet()
Sheets("SheetName").Copy After:=Sheets(Sheets.Count)
End Sub
Steps and Result: Replace "SheetName" with the actual sheet name you want to copy. This will create a
Move:-
Explanation: Moving a worksheet to a different position in the workbook.
Example Code:
Sub MoveSheet()
Sheets("SheetName").Move Before:=Sheets(1)
End Sub
Steps and Result: Replace "SheetName" with the actual sheet name you want to move. This will move t
Save As PDF:-
Explanation: Saving a specific worksheet as a PDF.
Example Code:
Sub SaveAsPDF()
Sheets("SheetName").ExportAsFixedFormat Type:=xlTypePDF, Filenam
End Sub
Steps and Result: Replace "SheetName" with the actual sheet name and "C:\Path\SheetName.pdf" with
specified sheet as a PDF file.
Steps and Result: Replace "yourpassword" with the desired password. Running this macro will protect a
UnProtect Worksheet:-
Explanation: Unprotecting a specific worksheet.
Example Code:
Sub UnProtectSheet()
Sheets("SheetName").Unprotect Password:="yourpassword"
End Sub
Steps and Result: Replace "SheetName" with the actual sheet name and "yourpassword" with the corre
Delete_Blank_Sheet:-
Explanation: Deleting all blank worksheets in the workbook.
Example Code:
Sub DeleteBlankSheets()
Dim ws As Worksheet
Application.DisplayAlerts = False
For Each ws In ThisWorkbook.Worksheets
If WorksheetFunction.CountA(ws.UsedRange) = 0 Then ws.Delete
Next ws
Application.DisplayAlerts = True
End Sub
Steps and Result: Running this macro will delete all blank worksheets in the workbook without displayin
3. IF Condition
IF…EndIF:-
Explanation: Basic If condition to perform a task if a condition is met.
Example Code:
Sub SimpleIf()
Dim x As Integer
x = 10
If x > 5 Then
MsgBox "x is greater than 5"
End If
End Sub
Steps and Result: Running this macro will display a message box if the value of x is greater than 5.
IF…Else…EndIF:-
Explanation: If-Else condition to perform tasks based on whether the condition is met or not.
Example Code:
Sub IfElse()
Dim x As Integer
x=3
If x > 5 Then
MsgBox "x is greater than 5"
Else
MsgBox "x is not greater than 5"
End If
End Sub
Steps and Result: Running this macro will display a message box saying "x is not greater than 5" because
Nested IF:-
Explanation: Using multiple If conditions within each other.
Example Code:
Sub NestedIf()
Dim x As Integer
x=7
If x > 5 Then
If x < 10 Then
MsgBox "x is between 5 and 10"
Else
MsgBox "x is greater than or equal to 10"
End If
Else
MsgBox "x is 5 or less"
End If
End Sub
Steps and Result: Running this macro will display a message box saying "x is between 5 and 10" because
4. Loops
For Next:-
Explanation: Looping a specific number of times.
Example Code:
Sub ForNextLoop()
Dim i As Integer
For i = 1 To 5
Cells(i, 1).Value = "Row " & i
Next i
End Sub
Steps and Result: Running this macro will fill cells A1 to A5 with the text "Row 1" to "Row 5".
Steps and Result: Running this macro will set the value of cell A1 in each worksheet to the sheet's name
Do While:-
Explanation: Looping as long as a condition is true.
Example Code:
Sub DoWhileLoop()
Dim i As Integer
i=1
Do While i <= 5
Cells(i, 1).Value = "Row " & i
i=i+1
Loop
End Sub
Steps and Result: Running this macro will fill cells A1 to A5 with the text "Row 1" to "Row 5".
Do Until:-
Explanation: Looping until a condition becomes true.
Example Code:
Sub DoUntilLoop()
Dim i As Integer
i=1
Do Until i > 5
Cells(i, 1).Value = "Row " & i
i=i+1
Loop
End Sub
Steps and Result: Running this macro will fill cells A1 to A5 with the text "Row 1" to "Row 5".
5. Error Handling
On Error Resume Next:-
Explanation: Skipping the line that causes an error and continuing with the next line.
Example Code:
Sub ResumeNext()
On Error Resume Next
' This will cause an error if there is no "Sheet1"
Sheets("Sheet1").Delete
' This line will still execute
MsgBox "Continuing after error"
End Sub
Steps and Result: Running this macro will try to delete "Sheet1". If it doesn't exist, it will skip the error a
Steps and Result: Running this macro will try to delete "Sheet1". If it doesn't exist, it will display the mes
Steps and Result: Running this macro will try to delete "Sheet1" and then "Sheet2". If either doesn't exis
Steps and Result: Running this macro will try to delete "Sheet1". If it doesn't exist, it will clear the error
Goto Jump:-
Explanation: Using GoTo for control flow.
Example Code:
Sub GoToJump()
Dim x As Integer
x=1
If x = 1 Then GoTo JumpHere
MsgBox "This will be skipped"
JumpHere:
MsgBox "This is after the jump"
End Sub
Steps and Result: Running this macro will skip the first message box and display "This is after the jump".
nced Topics
ts.Count)
want to copy. This will create a copy of the specified sheet at the end of the workbook.
want to move. This will move the specified sheet to the first position in the workbook.
pe:=xlTypePDF, Filename:="C:\Path\SheetName.pdf"
C:\Path\SheetName.pdf" with the desired path and filename. This will save the
e workbook.
nning this macro will protect all worksheets in the workbook with the specified password.
ourpassword"
yourpassword" with the correct password. This will unprotect the specified worksheet.
) = 0 Then ws.Delete
n't exist, it will skip the error and display the message box.
n't exist, it will display the message box "An error occurred".
s an error
"Sheet2". If either doesn't exist, it will handle the first error but stop at the second.
n't exist, it will clear the error state and display the message box.
FSO (FileSystemObject) is a powerful tool in VBA that allows you to manipulate files and folders. You
among other operations.
Data:
We'll use a base directory, C:\ExampleFolder, for our operations.
Example Codes:
1. Create Folder:
Objective: Create a folder if it doesn't exist.
Code:
Sub CreateFolder()
Dim fso As Object
Dim folderPath As String
2. Delete Folder:
Objective: Delete a folder if it exists.
Code:
Sub DeleteFolder()
Dim fso As Object
Dim folderPath As String
3. Copy Folder:
Objective: Copy a folder to a new location.
Code:
Sub CopyFolder()
Dim fso As Object
Dim sourceFolder As String
Dim destinationFolder As String
Results:
You will see message boxes confirming the creation, deletion, copying, and existence of folders an
Code Explanation:
FileSystemObject (FSO): An object that allows you to work with the file system.
CreateObject("Scripting.FileSystemObject"): Creates an instance of the FSO.
FolderExists(): Checks if a folder exists.
CreateFolder(): Creates a new folder.
DeleteFolder(): Deletes an existing folder.
CopyFolder(): Copies a folder to a new location.
FileExists(): Checks if a file exists.
CreateTextFile(): Creates a new text file.
DeleteFile(): Deletes an existing text file.
OpenTextFile(): Opens and reads a text file.
Sub CreatePivotTable()
Dim ws As Worksheet
Dim dataRange As Range
Dim pivotTable As PivotTable
Dim pivotCache As PivotCache
2. Pivot Charts
Explanation:
Pivot Charts allow you to visualize data from a Pivot Table in a graphical format. You can create Pivo
Example Code:
Objective: Create a Pivot Chart from a Pivot Table.
Code:
Sub CreatePivotChart()
Dim ws As Worksheet
Dim pivotTable As PivotTable
Dim chartObj As ChartObject
3. Create Chart:
Objective: Create a Chart from a data range.
Code:
Sub CreateChart()
Dim ws As Worksheet
Dim chartObj As ChartObject
4. Sparklines
Explanation:
Sparklines are mini charts within a single cell that provide a visual representation of data trends ove
Example Code:
Objective: Create Sparklines for a range of data.
Code:
Sub CreateSparklines()
Dim ws As Worksheet
5. Slicer
Explanation:
Slicers are visual filters that make it easier to filter data in Pivot Tables and Pivot Charts.
Example Code:
Objective: Add a Slicer to a Pivot Table.
Code:
Sub AddSlicer()
Dim ws As Worksheet
Dim pivotTable As PivotTable
Sub ApplyConditionalFormatting()
Dim ws As Worksheet
Code Explanation:
CreatePivotTable: Creates a Pivot Table from a specified data range and adds fields to it.
CreateChart: Creates a Chart from a specified data range and sets its type and title.
ApplyConditionalFormatting: Applies conditional formatting to a specified range based on a condi
Sub CreateAndRunVBScript()
Dim fso As Object
Dim filePath As String
Dim vbScript As String
8. User Forms
Explanation:
User Forms in VBA provide a graphical interface for user interaction. You can create forms to gather
interactive tasks.
Example Code:
Objective: Create a simple User Form to collect user input.
Steps:
1. Open the VBA editor (ALT + F11).
2. Insert a User Form (Insert > UserForm).
3. Add a TextBox and a CommandButton to the User Form.
4. Double-click the CommandButton to open the code window and add the following code:
Private Sub CommandButton1_Click()
MsgBox "Hello, " & TextBox1.Value & "!"
End Sub
9. Class Module
Explanation:
Class Modules in VBA allow you to create custom objects and define their properties, methods, and
components.
Example Code:
Objective: Create a simple class to manage student information.
Steps:
1. Open the VBA editor (ALT + F11).
2. Insert a Class Module (Insert > Class Module) and name it "Student".
3. Add the following code in the Class Module:
' Class Module: Student
Public Name As String
Public Age As Integer
ulate files and folders. You can create, delete, copy folders, and check if a folder exists,
sourceFolder & " to " & destinationFolder
sourceFolder
xtFilePath
textFilePath
nd existence of folders and text files as per the code executed.
se operators within functions to perform calculations or manipulate data. You can also
se operators within functions to perform calculations or manipulate data. You can also
As Double
rmat. You can create Pivot Charts to analyze and compare data more effectively.
Width:=375, Top:=50, Height:=225)
Pivot Charts.
ivotCache.Slicers.Add, SourceName:="Category", _
ft:=10, Height:=200, Width:=100)
used for simple tasks such as file manipulation, registry editing, and automation.
an create forms to gather user input, display information, and perform other
the following code:
properties, methods, and events. This helps in organizing code and creating reusable
:=targetSheet.Range("A1")
et in another workbook.
urceWorkbook.xlsx")
:=targetSheet.Range("A1")
ok to current workbook."
ourceWorkbook1.xlsx")
ourceWorkbook2.xlsx")
n:=targetSheet.Range("A1")
n:=targetSheet.Range("E1")