Professional Documents
Culture Documents
Click on Visual Basic/ Alt+F11 to switch into visual basic coding mode.
Project Explorer (Ctrl+R)
◦ Shows all the workbooks, sheets and modules.
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.
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
Break mode
Put a stop
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
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
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")
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
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)
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
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
Anything you write in button will be executed after clicking the button
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)
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
Call Shell("explorer.exe " & setpath, vbNormalFocus) '' opens the File
Object
DIM FSO
SET FSO = CREATEOBJECT ("SCRIPTING.FILESYSTEMOBJECT ")
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)
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
i=1
Var = origfile.ReadLine
ThisWorkbook.Sheets(1).Activate
Cells(i, 1) = Var
i=i+1
Loop
Sites
1 Stack Overflow
2 Excelexperts
Thanks
Parivesh Garg
(Executive Analyst)
AMA-DP Delhi