You are on page 1of 48

Customize the Ribbon- Click on Developer

Click on Visual Basic/ Alt+F11 to switch into visual basic coding mode.
Project Explorer (Ctrl+R)
◦ Shows all the workbooks, sheets and modules.

Properties Window (F4)


Insert a module through Insert-Module

A module will be created where you can write the


code.
You can change module’s name as per your convenience
Sub Nameofthemacro
End Sub
It will automatically create your End Sub

Name of the sub should not have any spaces or start


with any no/ special character just like dimension
Any syntax error in VBA will automatically be shown in red color.
Case insensitive

We can add comments with a ‘ just like dimension.


Comment/Uncomment Commands can be added to toolbar
View- Toolbars-Standard to add comment/uncomment toolbar
Basic VBA sentences

It works on principles of objects and methods

Object is worksheets and its methods will be cut, copy, paste, rename
Worksheets. After the dot, it will give you the list of functions just like VBA
(Intellisense list Hold Ctrl and press spacebar)
After dots, you can access any property displayed like font, color.

Worksheets.add (A new sheet will be added)

Range("a1").Value = 5
Range("a2").Value = "ABC"
Specifying Cell values
Range("a1:a6").Value = 5
Range("b1:b6").Value = "ABC"

Cells(4, 5) = "abc"
Range(Cells(1, 2), Cells(3, 4)) = "cell"

ActiveCell.Value = #2/3/2015#
[a1:b8] = 5

Range("a:a").Select
Go through Script

F8 to go into debug mode/step by step execution

Break mode

Put a stop

Ctrl+F9 after selecting statement to jump debugging


Defining Variables
TO DEFINE A NEW VARIABLE USE THE WORD DIM
EXAMPLE:
DIM A, B, C
DIM A, B AS STRING
DIM A AS INTEGER, B AS STRING

WRONG WAYS TO DEFINE A VARIABLE


DIM A=3
NOTE: IT IS NOT NECESSARY IN VBA TO DEFINE VARIABLES THROUGH DIM , YOU CAN
USE THEM AUTOMATICALLY.
* IT IS NECESSARY TO DEFINE VARIABLES WHILE USING
OPTIONEXPLICIT(OPTION EXPLICIT)
* IT IS NECESSARY TO DEFINE STRING VARIABLES
Selection of cells
Sub dfcd()
Range("a1").Select
ActiveCell.Value = 7599
End Sub
This will be updated in current active sheet, we need to specify the sheet we want to implement it.
If we want specific workbook/sheet then we should specify the name of workbook/sheet.

Workbooks.Open "M:\FAST\Macro Materials\Macrotrainingfile.xlsx"


Workbooks("Macrotrainingfile.xlsx").Activate
Workbooks("Macrotrainingfile.xlsx").Worksheets("Sheet2").Range("a1") = 6
(Activate brings it to the foreground unlike selection)
Refer to multiple cells
Sheet1.Range("a1:a6").Select
Selection.Interior.Color = rgbDarkBlue
Xl up/down/left/right
c=3
r = 10
Cells(4, c).End(xlToLeft).Select
Range("b" & r).End(xlUp).Select
Range("a1").End(xlDown).End(xlToRight).Select

ActiveCell.Offset(1, 1).Select
Range("c5").Offset(-1, -1).Select
Range("a1").End(xlDown).Offset(0, 4).Select
Rowno=cells(5,6).row
Columnno = Cells(5, 9).Column
Whole sheet rows and columns count
c = Columns.Count
r = Rows.Count
Range("A" & Rows.Count).End(xlUp).Select (Find last row or column using xl end and offset)
Copy and Paste
Sheet5.Activate
Range("a1").CurrentRegion.Copy

Sheet4.Activate
Range("a1").PasteSpecial

Columns("a:a").AutoFit
Rows(1).AutoFit
Workbooks access
Worksheets.add
Workbooks.Open "M:\FAST\Macro Materials\Macrotrainingfile.xlsx"

Workbooks("Macrotrainingfile.xlsx").Activate
Workbooks("Macrotrainingfile.xlsx").Worksheets("Sheet2").Activate
Workbooks("Macrotrainingfile.xlsx").Worksheets("Sheet2").Select
Workbooks("Macrotrainingfile.xlsx").Worksheets("Sheet2").Delete
Workbooks("Macrotrainingfile.xlsx").Sheets("Sheet1").Range("a2") = "w"
Workbooks("Macrotrainingfile.xlsx").Save
Workbooks("Macrotrainingfile.xlsx").Close
ThisWorkbook.Close (Close current Macro Workbook)
(You have to open workbook first before using any options like select/activate/delete)
Workbooks.Open "M:\FAST\Macro Materials\Macrotrainingfile.xlsx"
Activeworkbook.save
AP Example

Workbooks.Open "M:\FAST\Macro Materials\AP.xls"


Sheets("Tabs").Activate
Range("A1000").End(xlUp).Select
ActiveCell.Offset(0, 1).Select
Worksheets("guidelines").Delete
Worksheets.Add
Properties Window
1 Change the name
2 Visibility Property

Ways to Activate
Sheet9d.Activate (Left)
(The name which it identifies to activate is from properties window)
Or activate with name
Sheets("sheet9").Activate
Application.DisplayAlerts = False ‘’Does not display any alerts
Worksheets("sheet2").Delete
Application.ScreenUpdating = False (Does not show any screen fluctuations)

Sheets(2).Name = "d“
ThisWorkbook.Sheets("sheet2").Visible = True
ThisWorkbook.Sheets(2).Visible = True
Indexing
Sheets(4).Activate
4th sheet in order will be activated

To get the address of the Macro.


ToPath = ThisWorkbook.Path
Keyword SET

For creating a variable for range, we have to use set


Set myrang = Range("a1:a4")
myrang.Select

Set mynewbook = Workbooks.Add


mynewbook.Close

ActiveWorkbook.Sheets(2).Select
ActiveWorkbook.Sheets(2).Range("a1") = 4

Later use of set will be in creating objects and handling files/ folders.
Msgbox (Dialog Box)
MsgBox "Hello, this is my first macro " & Cells(1, 1).Address
a=5
MsgBox "The value of a is " & a & vbNewLine & "Thanks“"
a = MsgBox("frwege", vbYesNo)

If a = vbYes Then
MsgBox "yes"
Else: MsgBox "no"
End If
a=msgbox ("", (For all the options) (Press F1 and it will show all options)
(You can put title and other customizations in terms of type of message box)
Inputbox
To take input from user
age = InputBox("Please enter your age")

If age < 20 Then


MsgBox "Young"
Else: MsgBox "Old"
End If
It can be customized with one more parameter of type of value input.
Age = InputBox("Please enter your age", "Age")
Application.Inputbox

age = Application.InputBox("Please enter your age", "Age")

If age < 20 Then


MsgBox "Young"
Else: MsgBox "Old"
End If
Press F1 to input to know all its properties
(Application.Inputbox lets you interfere with excel while running unlike Inputbox)
i=1
Do Until i = 6
Cells(i, 1).Value = 20
i=i+1
Loop

i = 1 (Wrong Condition)
Do Until i < 0
Cells(i, 1).Value = 20
i=i+1
Loop
Ctrl+Pause/Break- To break out of the loop
Sub Functions

Sub dfvs()
Call sum2(4, 5)
End Sub

Sub sum2(a, b)
c=a+b
MsgBox "no is " & c
End Sub
Immediate Window

Hover over any variable, you could see its value while
program is running

Go to View- Immediate window


Print value of that variable

Locals Window
To check the values of variables while
Debugging.
Functions
Sheets(1).Range("a1:a16").ClearContents
Date
m = Month(Date)
y = Year(Date)
testdate = DateSerial(2010, 2, 3)
GoTo function is used to go to any label defined in program

Length
a = "fdfedf"
b = Len(a)
To find length of string
Find
Use Worksheet Functions
Excel Functions
a=5
b=6

c1 = Application.WorksheetFunction.sum(a, b)

Set myrang = Range("a1:a4")


myrang.Select
c = Application.WorksheetFunction.Count(myrang)

See locals window for all values


String Functions
R I G HT
E X T RAC T T HE R I G HTMOST CHA R AC T ERS
R = R I G HT("HEL LO", 1 )

LEFT
E X T RAC T T HE R I G HTMOST CHA R AC T ERS
LE F = LE F T ( "HEL LO", 1 )

L E N GTH
I T G I V ES T HE L E N GTH OF T HE ST RI NG
L E N G = L E N ( " HEL LO")
Combine strings & Variables
b = "name is"
a = "My " & b & " Parivesh"
MsgBox "" & a
Types of Loop
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Sheets
a = ws.Name
Next ws

Set myrang = Range("a1:a4")


myrang.Select
For Each cell In myrang
MsgBox "" & cell
Next cell
Exiting Loops

For x = 1 To 10
Cells(x, 1) = x
If x = 5 Then Exit For
Next x

i=1
Do Until i = 10
Cells(i, 1).Value = 20
i=i+1

If Cells(i + 1, 1).Value = 25 Then Exit Do


Loop
Insert a button

Anything you write in button will be executed after clicking the button

Adda button from insert tab


Assign a macro and then new
Sub Createnewsheet()

Worksheets.Add

End Sub
Find and Replace
Range("a1:a15").Find(What:="Cat", LookAt:= _
xlPart, MatchCase:=False, SearchFormat:=False).Activate
(Click on find and thn F1 to show its properties and use comma to identify parameters)
lookat= xlwhole or xlpart (xl part if in case you are fine if its a part of the whole string)

Range("A:A").Replace What:="_Code", Replacement:="", LookAt:=xlPart

Instr and Instrrev


a = "dfsfsdfdascsafde"
fo = InStr(1, a, "s") (fo value is 3)
lo = InStrRev(a, "s") (lo value is 12)
Instr function tells you the first occurrence and instrrev function tells you the last occurenece of specific character
Open File dialog box
NewFile = Application.GetOpenFilename("(*.txt;*.xls), ", , "Open my file", , True)

myfile = Application.GetOpenFilename("(*.txt;), ", , "Open excel file", , False)

Syntax of 1st parameter(File Filter): "(*.txt;*.xls), “


Title of Dialog Box: Open my file
True- If you want user to select multiple files

Asterisk see only the words enclosed between asterisks


Userform
INSERT AN USERFORM JUST LIKE
MODULE
USERFORMS-Types of Elements
LABEL
I T I S U S E D TO D I S P L AY S O M E T H I N G O N U S E R F O R M .
( P R O P E R T I E S C O U L D B E C H A N G E D BY P R O P E R T I E S W I N D O W )
( C L I C K O N TO O L B OX TO A C C E S S T H E S E TO O L S )
T E X T B OX
I T I S U S E D TO G E T S O M E I N P U T F R O M U S E R W H I L E F I L L I N G T H E U S E R F O R M .
F R O M PAT H = T E X T B OX 1 2 .VA LU E

C O M B I N AT I O N
E X A M P L E : G E T A N Y N A M E A S I N P U T.
P R I VAT E S U B C O M M A N D B U T TO N 1 _ C L I C K ( )
N A M E D S = T E X T B OX 1 .VA LU E
M S G B OX " M Y N A M E I S " & N A M E D S
END SUB
Types of Elements
COMB OBOX
I T S H OWS YO U T H E L I S T O F O PT I O N S A N D YO U C A N S E L EC T A N Y O N E .
( YO U C A N N OT F I L L I T M A N UA L LY )

P R I VAT E S U B U S E R FO R M _ A C T I VAT E ( )
CO M B O B OX 1 . A D D I T EM " 1 5 - 2 0 "
CO M B O B OX 1 . A D D I T EM " 2 0 - 3 0 "
CO M B O B OX 1 . A D D I T EM " 3 0 - 4 5 "
END SUB
I F CO M B O B OX 1 .VA LU E = " 1 5 - 2 0 " T H E N M S G B OX " YO U N G "
( P U T I T I N S U B O F U S E R FO R M A C T I VAT E , A S W E WA N T TO S E E I T A S W E S TA RT F I L L I N G O U R
U S E R FO R M )
D I S P L AY P RO P E RT I ES O F U S E R FO R M O R E L E M E N TS C A N B E C H A N G E D W I H T H E H E L P O F
P RO P E RT I ES W I N D OW. ( R EA D D P FO L D E R C R EAT I O N M A C RO A N D S P FO L D E R M A C RO )
Private Sub UserForm_Activate()
Label3.Visible = False
ComboBox2.Visible = False
ComboBox1.AddItem "Married"
ComboBox1.AddItem "Single"
ComboBox1.AddItem "Divorce"
End Sub
Private Sub CommandButton1_Click()
If ComboBox1.Value = "Single" Then
MsgBox "You are terminated" & vbCrLf & "Thanks for your time"
End If
End Sub
Private Sub ComboBox1_Change()
If ComboBox1.Value = "Married" Or ComboBox1.Value = "Divorce" Then
Label3.Visible = True
ComboBox2.Visible = True
ComboBox2.AddItem "1"
ComboBox2.AddItem "2"
ComboBox2.AddItem "3"
ComboBox2.AddItem "4"
End If
End Sub
Open any File/Folder
setpath = "C:\Users\Parivesh.Garg\Desktop\macro"

Call Shell("explorer.exe " & setpath, vbNormalFocus) '' opens the folder

setpath = "C:\Users\Parivesh.Garg\Desktop\Reference Codelist.xls"

Call Shell("explorer.exe " & setpath, vbNormalFocus) '' opens the File
Object
DIM FSO
SET FSO = CREATEOBJECT ("SCRIPTING.FILESYSTEMOBJECT ")

(ACTIVATE MICROSOFT RUN TIME LIBRARY IF SCRIPTING LIBRARY DOES N OT EXIST


RUN-> REFERENCES)

GET USERNAME
USERNAME= ENVIRON$("USERNAME")
USERNAME = REPLACE((ENVIRON$("USERNAME")), ".", " ")
Text file create
Dim FSO As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
Dim oFile As Object
Set oFile = FSO.CreateTextFile("C:\Users\" & Environ$("Username") & "\Desktop\" & "Job.ini")
oFile.WriteLine "#define PROJCODE " & Chr(34) & Chr(34)
oFile.WriteLine "#define ROOTLOCALE " & Chr(34) & "en-US" & Chr(34)
oFile.Close
Set FSO1 = Nothing
Set oFile = Nothing
Create bat file/mdd
Dim FSO As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
Create Bat file
Set oFile = FSO.CreateTextFile("C:\Users\" & Environ$("Username") & "\Desktop\" & "RunTables.bat")
oFile.WriteLine "#define PROJCODE " & Chr(34) & Chr(34)
Create mdd
Set oFile = FSO.CreateTextFile("C:\Users\" & Environ$("Username") & "\Desktop\" & "sp.mdd")
oFile.WriteLine "Metadata(en-US, Question, Label)"
oFile.WriteLine "End Metadata“
Create Folder
FSO.CreateFolder ("C:\Users\" & Environ$("Username") & "\Desktop\abcd")
Delete file and folder
Delete File
Call FSO.DeleteFile("C:\Users\" & Environ$("Username") & "\Desktop\RunTables.bat" & "*",
True)
Call FSO.DeleteFolder("C:\Users\Parivesh.Garg\Desktop\Macro\new" & "*", True)

Call FSO.DeleteFolder("C:\Users\" & Environ$("Username") & "\Desktop\abcd" & "*", True)


(Asterisk if there is any special character in the path)
True is for deleting even if folder is read only
Copy file and folder
FSO.CopyFile ("C:\Users\Parivesh.Garg\Desktop\Job.ini"),
"C:\Users\Parivesh.Garg\Desktop\Macro\", True

FSO.CopyFolder ("C:\Users\Parivesh.Garg\Desktop\new"),
"C:\Users\Parivesh.Garg\Desktop\Macro\", True
To Check File/Folder Exists
Dim FSO As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FolderExists("C:\Users\Parivesh.Garg\Desktop\new") = False Then
MsgBox FromPath & " doesn't exist"
Exit Sub
End If
If FSO.fileExists("C:\Users\Parivesh.Garg\Desktop\Reference Codelist - Copy.xls") = False Then
MsgBox FromPath & " doesn't exist"
Exit Sub
End If
If Dir("C:\Users\Parivesh.Garg\Desktop\Reference Codelist - Copy.xls") = "" Then
MsgBox FromPath & " doesn't exist"
Exit Sub
End If
Read mdd
Dim fso As Scripting.FileSystemObject

Set fso = New FileSystemObject

Dim origfile As Scripting.TextStream

Set origfile = fso.opentextfile("M:\FAST\Macro Materials\ADXR4R.mdd")

i=1

Do While Not origfile.AtEndOfStream

Var = origfile.ReadLine

ThisWorkbook.Sheets(1).Activate

Cells(i, 1) = Var

i=i+1

Loop

Tools-> References-> Microsoft Scripting Run Time


Error Handling
ON ERROR GOTO ERRORHANDLER
ERRORHANDLER:

ON ERROR RESUME NEXT (IGNORE ERROR AND MOVE)

ON ERROR RESUME NEXT


WORKSHEETS("SHEET21").DELETE
MSGBOX "YES"
References
Video Tutorials
1 Wiseowl
https://www.youtube.com/watch?v=K0VqyXLJBOw&index=8&list=PLw8O1w0Hv2ztGjIkrW7suD6oNDaOk3vbR
2 Excel Vba fun
https://www.youtube.com/channel/UC9OIUFZfYqELCFwWxT7OpKQ

Sites
1 Stack Overflow
2 Excelexperts
Thanks
Parivesh Garg
(Executive Analyst)
AMA-DP Delhi

You might also like