Macros 90
Macros 90
Macros 90
What is VBA?
Visual Basic for Applications, it is programming languages with the help of VBA you can automate the
tasks in excel by writing so called Macros.
What is Macro?
Macro is set of instruction which is stored in visual basic module which can make excel to perform
commands and actions for you by running them
Code Group:
Note: The same shortcut is used to switch between excel and VB editor
Macro: A program that can be recorded/written in order to automate the manual process.
Recording Macros:
1. Select a cell.
2. Choose Developer → Code → Record Macro or click the macro recording button on the status bar.
Excel provides a default name (something like Macro1), but it’s better to use a more descriptive name.
NameAndTime (with no spaces) is a good name for this macro.
4. Click the Shortcut Key box, and enter Shift+N (for an uppercase N) as the shortcut key.
Specifying a shortcut key is optional. If you do specify one, you can execute the macro by pressing a key
combination — in this case, Ctrl+Shift+N.
6. You can enter some text in the Description box, if you like.
This step is optional. Some people like to describe what the macro does (or is supposed to do).
7. Click OK.
The Record Macro dialog box closes, and Excel’s macro recorder is turned on. From this point, Excel monitors
everything you do and converts it to VBA code.
9. Move the cell pointer to the cell below and enter this formula:
=NOW()
10. Select the formula cell, and press Ctrl+C to copy that cell to the Clipboard.
11. Choose Home → Clipboard → Paste → Values (V).
12. With the date cell selected, press Shift+up arrow to select that cell and the one above it (which contains
your name).
13. Use the controls in the Home → Font group to change the formatting to Bold and make the font size 16
point.
Store macro in: determines the workbook that saves the macro:
Name:Personal.xls(b)
b-binary
thisworkbook.Path
Use Relative References: is used to record macros so that they run with references to the active cell
Macro Security
Disable all macros with notification: Displays a security alert when a workbook with macros opens. You can
then decide whether to enable the macros associated with the workbook. This is the Excel default setting.
Disable all macros except digitally signed macros: You can run only those macros that are digitally signed.
Enable all macros: Allows macros to run without a notification. This can be helpful if you run a lot of macros,
but be aware of the risk when using macros from unknown sources.
Protect Macro:
VBE->Tools->VBAProject Properties
Private Sub sets the scope so that subs in outside modules cannot call that particular
subroutine. This means that a sub in Module 1 could not use the Call method to initiate a Private
Sub in Module 2.
Public Sub means that your subroutine can be called or triggered by other subs in different
modules. Public is the default scope for all subs so you do not need to add it before the word
“sub”.
MsgBox Function
Part Description
prompt Required. String expression displayed as the message in the dialog box. The maximum length of prompt is approximately 1024
characters, depending on the width of the characters used. If prompt consists of more than one line, you can separate the lines
using a carriage return character (Chr(13)), a linefeed character (Chr(10)), or carriage return linefeed character combination
(Chr(13) &Chr(10)) between each line.
buttons Optional. Numeric expression that is the sum of values specifying the number and type of buttons to display, the icon style to use,
the identity of the default button, and the modality of the message box. If omitted, the default value for buttons is 0.
title Optional. String expression displayed in the title bar of the dialog box. If you omit title, the application name is placed in the title
bar.
helpfile Optional. String expression that identifies the Help file to use to provide context-sensitive Help for the dialog box. If helpfile is
provided, context must also be provided.
context Optional. Numeric expression that is the Help context number assigned to the appropriate Help topic by the Help author.
If context is provided, helpfile must also be provided.
vbApplicationModal 0 Application modal; the user must respond to the message box
before continuing work in the current application.
vbSystemModal 4096 System modal; all applications are suspended until the user
responds to the message box.
vbMsgBoxHelpButton 16384 Adds Help button to the message box
VbMsgBoxSetForeground 65536 Specifies the message box window as the foreground window
vbOK 1 OK
vbCancel 2 Cancel
vbAbort 3 Abort
vbRetry 4 Retry
vbIgnore 5 Ignore
vbYes 6 Yes
vbNo 7 No
Components in VB editor:
Project Explorer(ctrl+R):Displays all open workbooks as vba projects.each vba project consist of sheet
1,2,3..& this workbook (MS excel objects)
Properties window (F4):displays the properties of the selected item, and enables the user to modify
?10+20
Locals window:
Automatically displays all of the declared variables in the current procedure and their values.When
the Locals window is visible, it is automatically updated every time there is a change from Run to Break
mode or you navigate in the stack display
VARIABLE
A variable is a name that you type into a Macro that you can use to store information, be it text or numbers.
Once you put information into the variable, you can later reference that variable in order to get the information
that is stored within it.
You can reference a variable as many times as you need throughout a macro and you can also change the
data that is contained within it as many times as you need. You control what's in the container.
They must begin with a letter
They must contain only letter, numbers or the underscore character –no spaces!
They must not exceed 40 characters
They must not be a reserved word
Data Types:
Variant:
A Variant can store all kinds of data, whether it is text, numbers, dates or other information. It can even
store entire array. A variant variable can freely change it type at runtime
You can use function varitype to find out the type of data held by a variant:
Temp=”david”
Msgbox temp
Temp=8
Msgbox temp
End sug
0 Variant
1 Null
2 Integer
3 Long
4 Single
5 Double
6 Currency
7 Date/Time
8 String
11 Boolean
17 Byte
You can use the IsNumeric function to test if the value of a variant is number-if returns true or false
You can use the IsDate function to determine if there is a date value
Isempty,Isnull
Byte: A data type used to hold positive integer numbers ranging from 0 to 255
Integer: A data type that holds integer variables stored as 2-byte whole numbers in the range -32,768 to 32,767.
The Integer data type is also used to represent enumerated values. The percent sign (%) type-declaration character
represents an Integer in Visual Basic
Sub Numberofrows()
Numberofrows=worksheets(1).rows.count
Msgbox numberofrows
End sub
Sub floats
Floatingpoing =10/3
Msgbox floatingpoint
End sub
Boolean: True/False
Operators:
Arithmetic Operators:
Exponentiation(˄)
Multiplication and division (*,/) multiply the numbers, / The division operator
Integer division (\):The integer division operator (divides two numbers and returns the integer result -
e.g. 7\4 gives a result of 1)
Modulo arithmetic (Mod) :The modulus operator (divides two numbers and returns the remainder - e.g.
8 Mod 3 gives a result of 2)
Comparison
Operator Meaning
= Equal to
Logical Operators
And
Or
Not
Xor
Other Operators
Like operator
Like compares two string expressions that are similar to each other to see if they match a pattern. They
may have the first few characters the same or may simply be in uppercase and lowercase
Sub text
End sub
Functions
X=”123excel”
Z=mid(x,4)
Msgbox z
End Sub
X=Ucase(“excel”)
X=Lcase(“EXCEL”)
Start is an optional parameter and shows where in the string the omit search should start from, if it
omitted the search starts from position 1. Start must not contain a null value, and if start is used then
the compare parameter must be used.
Compare: compare is the technique used to compare the strings, The possible values are
vbBinaryCompare and vbTextcompare. In simple terms. This determines whether the search is case
sensitive or not.
Binary compare uses actual binary values, so A equal A, Text compare ignores case, so A will equal a
?instr(1,"oracle","RA",vbTextCompare)
Replace: Replace(string,find,replace)
->case sensitive
?Isnumeric(“123”)
True
?isnumeric(“a123’)
False
?val(“a123”)
123
True
?isdate(“29-feb-2017”)
False
?now(): The now function returns the current date and time
6/11/2016 8:16:17 PM
6/11/2016
DateAdd: DateAdd allows the addition and subtraction of a specified time interval to a date.
Syntax: DateAdd(interval,Number,date)
Year Yyyy
Quarter Q
Month M
Day of Year Y
Day D
WeekDay W
Week Ww
Hour H
Minute N
Second S
Msgbox DateAdd(“m”,1,’1-Jan-2016”)
DateDiff: The DateDiff function returns the number of time intervals between two specified dates:
Msgbox DateDiff(“m”,”1-Jan-2016”,”15-Mar-2016”)
Syntax: Datepart(Interval,Date)
Msgbox Datepart(“q”,”1-Mar-2016”)
Day: This will return an integer between 1 to 31, representing the day of the month for the date
expression.
Day(Dateexpression)
?Day(“1-feb-2016”)->1
Month(dateexpression)
?Month(“1-feb-2016”)->2
Weekday: The function returns an integer between 1(Sunday) and 7 (Saturday) that represents day of
the week for a date expression:
?weekdayname(1)->Sunday
?weekdayname(weekday("12-June-2016"))
Sunday
Monthname:
Syntax:Monthname(1)
January
monthname(month(date))
?monthname(month("1-June-2016"))
?Time()->12 hr format
?Hour(time)->Hour returns between 0 and 23 representing the hour of the day for the date expression
Hour(dateexpression)
Msgbox Hour(“17:50”)
16
Minute: The Minute function returns an integer from a time expression representing the actual minute
of that time
Msgbox Minute(11.25/24)
?minute("17:50")
Excel Object Model: The internal structure of excel through which vba programs can operate excel
objects
Application:Excel
Sheets(Index/Name):specific sheet
Cells(rowindex,columnindex):Specific cell
Syntax:Object Name.Property/Method
Eg:sheets.count
Range Object
Sub range_select()
‘Method
‘Note: range(“a1”).property/Method
Range(“a10”).select
Range(“a10,A5:a7”).select
Range(“a:a”).select
Range(“A:c,F:F,H5:H10”).select
Range(“1:1”).select
Range(“1:3,10:15,f:f”).select
Cells.select
Cells(2,10).select
Cells(2,”J”).select
End sub
Sub ActivateMethod()
Range(“a1:a5”).select
Range(“a3”).activate
Range(“b3”).activate
End sub
Sub Valueex()
Range(“a1”).value=10
Range(“a2”).value=#6/3/2016#
Range(“a:a”).columns.autofit
End sub
Sub Differentwaytoreferarange()
Range(“b1”)=1
Cells(2,2)=2
Cells(3,”b”)=3
[b4]=4
Evaluate(“b5”)=5
Evaluate(“b5:b10”)=5
End sub
Sub clearmethods()
Cells.Clear 'all
Cells.ClearComments
Cells.ClearFormats
End Sub
Range("a1:a6").Cut Range("b6")
End Sub
Activate Method:
"many cells can be selected, but only one may be the active cell at any given time."
Sub activatevsselect()
Sheets(Array("Sheet1", "Sheet2")).Select
Sheets("Sheet2").Activate
End sub
Sub activatemethod()
Range("a1:a5").Select
Range("a3").Activate
Range("b3").Activate
Range("b4:b10").Select
Range("b8").Activate
End Sub
Sub activatemethod()
Range("A1").Value = 10
Range("A2").Value = #6/23/2016#
Range("a:a").Columns.AutoFit
End Sub
Sub DiffwaysToReferRange()
Range("b1") = 1
Cells(2, 2) = 2
Cells(3, "b") = 3
[b4] = 4
Evaluate("b5") = 5
Evaluate("b5:b10") = 6
End Sub
Sub clearmethod()
Cells.Clear 'All
Cells.ClearComments
Cells.ClearFormats
End Sub
Sub cutmethod1()
Range("a1:a10").Cut Range("c1")
End Sub
Sub cutmethod2()
Sheets("Sheet1").Range("a1:a10").Cut Sheets("Sheet2").Range("c1")
Sheets("Sheet2").Activate
End Sub
Sub cutmethod3()
Workbooks("Book2").Sheets("Sheet1").Range("a1:a10").Cut _
Workbooks("Book1").Sheets("Sheet1").Range("c1")
Workbooks("Book2").Sheets("Sheet1").Activate
End Sub
Sub copymehthod()
Range("a1:a10").Copy Range("d1,g5,f2")
End Sub
Range("a1:a10").Copy
Range("b1").PasteSpecial
Range("c1").PasteSpecial xlPasteValues
Range("d1").PasteSpecial xlPasteValuesAndNumberFormats
Range("e1").PasteSpecial xlPasteFormats
Range("f1").PasteSpecial xlPasteFormulas
Range("g1").PasteSpecial xlPasteFormulasAndNumberFormats
Range("h1").PasteSpecial xlPasteComments
Range("i1").PasteSpecial xlPasteAllExceptBorders
Application.CutCopyMode = False
Columns.AutoFit
End Sub
‘pastespecial operations
Sub pastespecailoperations()
Range("a1:a10").Copy
Range("b1").PasteSpecial operation:=xlPasteSpecialOperationMultiply
Application.CutCopyMode = False
End Sub
Sub multi11p1()
Range("d1").Copy
Range("a1:a10").PasteSpecial operation:=xlPasteSpecialOperationAdd
Application.CutCopyMode = False
End Sub
Sub transpose()
Range("a1:a10").Copy
Range("b1").PasteSpecial transpose:=True
Application.CutCopyMode = False
End Sub
Sub skipblanks()
Range("a1:a10").Copy
Range("b1").PasteSpecial Skipblanks:=True
Application.CutCopyMode = False
End Sub
Syntax:inputbox(Prompt,[title],[default])
Sub readvaluesfromuser()
End Sub
Sub withoutwith()
ActiveCell.Font.Name = "Arial"
ActiveCell.Font.Color = vbBlue
ActiveCell.Font.Size = 50
ActiveCell.Font.Italic = True
ActiveCell.Font.Bold = True
End Sub
Sub usingwithstatment()
With ActiveCell.Font
.Bold = True
.Size = 50
.Color = vbBlue
.Italic = True
.Name = "Arial"
End With
End Sub
Sub withex()
With Sheets("Sheet1")
a = .Range("a1")
b = .Range("b1")
.Range("c1") = "The result is " & a + b
End With
End Sub
Conditional Statements
Syntax:
Sub iifex()
Dim a As Integer
Dim b As Integer
a = 10: b = 20
End Sub
Sub iffex2()
'leap check
Dim y As Integer
y = Range("a1")
End Sub
Sub usernamepwdcheck()
End Sub
Sub usernamepwdcheck()
End Sub
IF statement:
If can validate one/more conditions. i.e..it works against simple or complex criteria & executes code
accordingly
Syntax:
If condition1 then
Code
Code
Code
---
--
[else code]
End if
Note: IF Statement is written in a single line, end if is not required
Sub calculatecommission()
salesamount = Range("a1")
If salesamount >= 100000 Then commission = salesamount * 0.5 Else commission = 1000
Range("a2") = Round(commission, 2)
End Sub
Sub results()
score = Range("a1").Value
Range("b1").Value = result
End Sub
Sub results()
score = Range("a1").Value
Range("b1").Value = result
End Sub
Sub calculatecommissionmulti()
salesamount = Range("a1")
Else
commission = 1000
End If
Range("a2") = Round(commission, 2)
End Sub
Sub calculatecommissionelseif()
salesamount = Range("a1")
Else
commission = 1000
End If
Range("b1") = Round(commission, 2)
End Sub
Sub Nestedif()
m1 = Range("a2")
m2 = Range("b2")
m3 = Range("c2")
tot = m1 + m2 + m3
avg = Round(tot / 3, 2)
'to find out whether the student has secured pass marks
result = "A"
result = "B"
Else
result = "c"
End If
Else
result = "Fail"
End If
Range("d2") = tot
Range("e2") = avg
Range("f2") = result
End Sub
Sub replacement()
Dim i As Integer
For i = 2 To lastrow
b = Range("a" & i)
a = WorksheetFunction.Match(b, Range("g2:g5"), 0)
If a > 0 Then
End If
Next
Application.CutCopyMode = False
End Sub
Sub Markscheck()
sngmarks = 60
MsgBox "Excellent"
MsgBox "Good"
MsgBox "Average"
Else
MsgBox "Poor"
End If
End Sub
Select case: it can take one input and validates it against a set of cases and executes the code
accordingly
Case expected-val1:code
Case expected-val2:code
Case else:code
End select
Sub DisplayweekdayName()
Dim w As Integer
w = InputBox("Enter a number")
Select Case w
End Select
End Sub
Sub pantype()
panid = Range("a1")
End Select
Range("b1") = pantype
End Sub
Sub getconfhall()
deptno = Range("a1")
Range("b1") = confhall
End Sub
Sub scorecheck()
score = Range("a1")
Case Is >= 80
Case Is >= 70
result = "good"
Case Is >= 60
result = "sufficient"
Case Else
result = "Insufficient"
End Select
Range("b1").Value = result
End Sub
For..Next Loop: Loops are used to repeat a block of code as many time as required, until a given
condition true or a specific point(or value) is reached. After which the next section of code is executed.
{…statements..}
Next counter
Increment: optional. The value that counter is incremented each pass through the loop. It can be
positive or negative number. if not specified it will default to an increment to 1 so that pass through the
loop increase counter by 1
Statements: the statements of code to execute each pass through the loop
Sub loopexample()
endnumber = 5
MsgBox strnumber
Next strnumber
End Sub
Sub forex()
Dim i As Integer
For i = 1 To 10
Sheets("Sheet1").Range("a" & i) = i
Next
End Sub
Sub simplenextloop()
For loopcount = 1 To 10
Next loopcount
End Sub
Sub forex5()
Dim i As Integer
For i = 1 To 10
'Sheets("Sheet1").Range("A" & i) = i
'Sheets("Sheet1").Cells(i, "A") = i
Sheets("Sheet1").Cells(i, 1) = i
Next i
End Sub
Sub forex6()
Dim n As Integer
n = InputBox("enter a number")
Cells.Clear
r = 1: c = 1
For i = 1 To n
Cells(r, c) = i
r=r+1
If r = 11 Then
r=1
c=c+1
End If
Next
End Sub
Sub primecheck()
'eg: 2,3,5,7,11,13....
n = Range("a1")
For i = 1 To n
If n Mod i = 0 Then
zerocount = zerocount + 1
End If
Next
If zerocount = 2 Then
Range("a2") = "prime"
Else
End If
End Sub
Sub print2ndmulti()
Dim i As Integer
Cells.Clear
For i = 1 To 10
Next i
End Sub
Sub printnthtable()
Dim i As Integer
n = InputBox("Enter a number")
Cells.Clear
For i = 1 To 10
Next i
End Sub
Sub protectworksheets()
numberofworksheets = Worksheets.Count
Worksheets(loopcounter).Protect
'Worksheets(loopcounter).Unprotect
Next loopcounter
End Sub
Sub workbooksclose()
Numofbooks = Workbooks.Count
Workbooks(loopcounter).Close
Next loopcounter
End Sub
Sub FortnightDates()
lastrow = Range("a1").End(xlDown).Row
For i = 1 To lastrow
If Day(Range("a" & i)) >= 1 And Day(Range("a" & i)) <= 15 Then
Range("b" & i).Value = "1-15th " & Format(Range("a" & i), "MMM-YY")
ElseIf Day(Range("a" & i)) >= 16 And Day(Range("a" & i)) <= 31 Then
Range("b" & i).Value = "16- " & Day(Application.WorksheetFunction.EoMonth(Range("a" & i), 0)) & " "
& Format(Range("a" & i), "MMM-YY")
End If
Next i
End Sub
Sub Replacementvalues()
lastrow = Range("a1").End(xlDown).Row
For i = 1 To lastrow
If a > 0 Then
End If
Next
Application.CutCopyMode = False
End Sub
Nested Loops:
Note: for each cycle in OUTER LOOP, all cycles of INNER LOOPS are executed
Sub print1to20Mtables()
Cells.Clear
For n = 1 To 20 'Outer
For i = 1 To 20 'inner
Next i
Next n
Columns.AutoFit
End Sub
Sub listofprimenosbetween1to100()
Cells.Clear
For n = 1 To 100
For i = 1 To n
If n Mod i = 0 Then
zerocount = zerocount + 1
End If
Next i
If zerocount = 2 Then
rno = rno + 1
Cells(rno, 1) = n
End If
zerocount = 0
Next n
End Sub
Sub pyramid()
Next j
Next i
End Sub
Sub pyramid1()
Next j
Next i
End Sub
Next variable_Name
Note: SET keyword must be used while assigning/removing a reference to/from an object variable
Sub sheetproperties()
Dim ws As Worksheet
Set ws = Sheets("Sheet2")
ws.Name = "Info1"
ws.Tab.ColorIndex = 3
Set ws = Nothing
End Sub
Sub getlistofsheets()
'from activeworkbook
Cells.Clear
i=i+1
Next
Columns.AutoFit
Set sh = Nothing
End Sub
Sub getlistofopenworkbooks()
Cells.Clear
i=i+1
Next
Columns.AutoFit
Set wb = Nothing
End Sub
Sub loopthrougranges()
Dim c As Range
Debug.Print c.Address
Debug.Print c.Value
Next
Set c = Nothing
End Sub
Sub Extractnumbers()
num = ""
For i = 1 To lastrow
End If
Next i
Next j
End Sub
Color index:
Default color:56
Property: Colorindex
Custom colors:16M
Property:color
Activecell.interior.colorindex
--To Font---
Activecell.font.colorindex
Note:RGB(Red,Green,Blue); is used to set custom colors
Sub colorcodes()
Dim i As Integer
For i = 1 To 56
Next
End Sub
Sub regeg()
End Sub
Sub fontcolurs()
Range("e1").Font.ColorIndex = 3
Range("f1").Font.Color = 16077040
End Sub
?activesheet.usedrange.address
?activesheet.usedrange.select
‘First row
?Activesheet.usedrange.row
‘First column
?Activesheet.usedrange.column
‘No of rows
?activesheet.usedrange.rows.count
‘No of columns
?activesheet.usedrange.columns.count
Sub Delblankrows()
lrow = ActiveSheet.UsedRange.Rows.Count
Dim r As Long
If Application.WorksheetFunction.CountA(Rows(r)) = 0 Then
Rows(r).Delete
End If
Next
End Sub
Sub selectcellsdiagonally()
Dim i As Integer
For i = 1 To n
Else
' End If
Next
Range(str).Select
End Sub
Sub Repeatvalues()
rpt = c.Next.Value
For i = 1 To rpt
Cells(rowno + i, 3) = c.Value
Next
Next
Set c = Nothing
End Sub
Sub namecheck()
Dim c As Range
'c.Next.Value = "Found"
c.Offset(0, 1) = "Found"
End If
Next
Set c = Nothing
End Sub
Syntax:
‘While condition
‘code
‘wend
Sub print1to10()
Dim i As Integer
While i < 10
i=i+1
Cells(i, 1) = i
Wend
End Sub
Do..While loop
It is condition based
It is a post check loop, i..e. it checks the condition after each cycle
Syntax:
Do
Code
Sub dowhileloop()
x=2
Do While Cells(x, 2) <> ""
x=x+1
Loop
End Sub
Sub calcommission()
Do
Else
comm = 1000
End If
choice = MsgBox("Sales amount" & samt & vbNewLine & "commisso" & comm & vbNewLine & "Do
u want to continue?", vbYesNo)
End Sub
GOTO: Change the flow of the program
Sub goto1()
Dim a As Integer
a = 25
GoTo checkvalue
a = 50
checkvalue:
MsgBox a
End Sub
Sub delblanksheet()
Dim sh As Worksheet
Application.DisplayAlerts = False
sh.Delete
End If
Next sh
'reset
End Sub
Method 1:
Range.End
Sub Find_last_row_column()
'Cells(1, Columns.Count).End(xlToLeft).Select
End Sub
Sub s2()
b = Cells(1, Columns.Count).End(xlToLeft).Column
End Sub
Method 2:
Range.Find
-Blanks Ok
Find Method starts in first cell and searches in previous order. Goes directly to lastcell in worksheet
and searches each row moving right to left and bottom to top until it finds a non-blank cell.
Sub range_find_method()
lrow = Cells.Find(What:="*", _
lookat:=xlPart, _
LookIn:=xlFormulas, _
searchorder:=xlByRows, _
searchdirection:=xlPrevious, _
MatchCase:=False).Row
End Sub
Method 3:
Range.Specialcells
Ctrl+End
Sub range_specialcells()
MsgBox Range("a1").SpecialCells(xlCellTypeLastCell).Address
End Sub
Sub Myloopup1()
emp_name = "Noah"
End Sub
Sub Myloopup2()
Else
End If
Exit Sub
MyerrorHandler:
End If
End Sub
Sub mylookup3()
For i = 2 To lastrow
Next i
End Sub
There are two ways to connect Excel with another application, Early Binding and Late Binding. Early
Binding sets the connections between Excel and the other application early in the process, i.e., during
design time. In Late Binding, the connection isn't made until later, during run time. In general, Early
Binding is the preferred method.
Early Binding has several advantages. Because the Object Model of the other application is known to
Excel during development, the developer can make use of Intellisense and the Object Browser to help
write his code. The developer can also compile the code to assure there are no syntax errors. And
finally, Early Bound procedures run a little faster
->The first important step to enable Excel to use Early Binding to interact with other applications is to
set a reference to the other application's object library. In the Visual Basic Editor (VBE),
select References... from the Tools menu
->fast
Late Binding:
Late Binding does not allow the developer to use many programming and debugging tools, such as
Intellisense, the Object Browser, and compiling. Late Bound code also runs more slowly than Early
Bound code. The advantage to Late Binding is that the developer does not have to worry about the
wrong version of an object library being installed on the user's computer. For example, if I know my
client will be automating Word, but I don't know which version.
->creating an object of target type using create object
->eg: CreteObject(“word.application”)
->Slow
Sub wordex()
'Late binding
Dim W As Object
Dim d As Object
Set W = CreateObject("Word.Application")
W.Visible = True
Set d = W.Documents.Add
d.SaveAs "C:\Users\Welcome\Desktop\sample.docx"
d.Close
W.Quit
Set d = Nothing
Set W = Nothing
End Sub
Sub wordex1()
'Early binding
Dim d As Word.Document
W.Visible = True
Set d = W.Documents.Add
d.SaveAs "C:\Users\Welcome\Desktop\test.docx"
d.Close
W.Quit
Set d = Nothing
Set W = Nothing
End Sub
Sub driverex()
Dim fs As Object
Set fs = CreateObject("Scripting.Filesystemobject")
Dim d, i As Integer
i=i+1
Cells(i, 1) = d
Next
Set d = Nothing
Set fs = Nothing
End Sub
Sub Listoffoldersfromselectedfolder()
Set fs = CreateObject("Scripting.Filesystemobject")
Dim d, i As Integer
Cells.Clear
i=i+1
Cells(i, 1) = d.Name
Next
Set d = Nothing
Set fs = Nothing
End Sub
Sub listoffileswithaattribuesfromselectedfolder()
Set fs = CreateObject("Scripting.Filesystemobject")
Dim d, i As Integer
i=1
Cells.Clear
Cells(i, 1) = "Name"
Cells(i, 2) = "Type"
Cells(i, 3) = "size"
Cells(i, 4) = "extensions"
Cells(i, 7) = "Path"
For Each d In fol.Files
i=i+1
Cells(i, 1) = d.Name
Cells(i, 2) = d.Type
Cells(i, 3) = d.Size
Cells(i, 4) = fs.GetExtensionName(d.Name)
Cells(i, 5) = d.DateCreated
Cells(i, 6) = d.DateLastModified
Cells(i, 7) = d.Path
Next
Set d = Nothing
Set fs = Nothing
Columns.AutoFit
End Sub
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
folpath = .SelectedItems(1)
End With
MsgBox folpath
Set fs = Nothing
End Sub
Sub getfol()
With Application.FileDialog(msoFileDialogFilePicker)
.Title = "select"
.Show
Dim f, i As Integer
i=i+1
Next
Set f = Nothing
End With
Set fs = Nothing
End Sub
INSTRREV: The Microsoft Excel INSTRREV function returns the position of the first occurrence
of a string in another string, starting from the end of the string.
Sub filters()
With Application.FileDialog(msoFileDialogFilePicker)
'syntax:filters.add descritpion.extensions
.Show
Cells(1, 1) = .SelectedItems(1)
End With
End Sub
Working with existing workbooks
To open
Workbooks.open filename
To save
ActiveWorkbook.save
To save as
Activeworkbook.savesas filename
To close
Activeworkbook.close
Workbooks.add
Sub DeleteBlankSheetsFromallFiles()
folpath = InputBox("folderpath")
Set fs = CreateObject("Scripting.Filesystemobject")
Dim sh As Worksheet
Application.DisplayAlerts = False4
Workbooks.Open f.Path
sh.Delete
End If
Next sh
ActiveWorkbook.Save
ActiveWorkbook.Close
End If
Next f
End Sub
Sub CreateTextFileEx()
Set fs = CreateObject("Scripting.Filesystemobject")
Set f = fs.createtextfile("C:\Users\Welcome\Desktop\sample.txt")
Set f = Nothing
Set fs = Nothing
End Sub
Sub Overwritetextfile()
Set fs = CreateObject("Scripting.Filesystemobject")
f.writeline "one"
f.writeline "two"
Set fs = Nothing
Set f = Nothing
End Sub
Sub writeallcommentsfromcurrentsheetintoatextfile()
Set fs = CreateObject("Scripting.Filesystemobject")
Set f = fs.createtextfile("C:\Users\Welcome\Desktop\ssss.txt")
Dim c As Range
f.writeline c.Address
f.writeline c.Comment.Text
Next c
Set f = Nothing
Set fs = Nothing
End Sub
Sub wordcountext()
str = Application.WorksheetFunction.Trim(Range("a1"))
wcount = 1
End If
For i = 1 To Len(str)
wcount = wcount + 1
End If
Next
End Sub
Arrays
An array is a group of variables with the same data type and name.
Or
Syntax:
Sample declarations:
Single:
Note:1->lowerbound
Note:11->upperbound
Note:Lbound and Ubound functions are used to find out lowerbond and upperbound of
arrays
Two dimensions:
Multi dimensions:
Option Base: statement determines the lowebound of all implicit arrays in all programs in a
module
Option Base is a module level statement it must be written at the top of the module
Option Base 1
Sub sss()
a(1) = 10
a(2) = 20
a(3) = 30
MsgBox LBound(a)
MsgBox UBound(a)
End Sub
Option Base 1
Sub array2()
Dim i As Integer
Next
Next
Range("a6") = tot
End Sub
Sub swapex1()
a = 10
b=3
tempval = a
a=b
b = tempval
MsgBox a
MsgBox b
End Sub
Sub swapex2()
a = 10
b=3
a = a + b '13
b = a - b '10
a=a-b '13-10=3
MsgBox a
MsgBox b
Next
tempval = a(i)
a(i) = a(j)
a(j) = tempval
End If
Next j
Next i
Next
End Sub
Option Base 1
Sub arrydynamically()
'Dynamic arrays:
ReDim a(Range("a1").End(xlDown).Row)
End Sub
Sub consolidatefirstandlastcolumsinfromeachsheet()
Dim ws As Worksheet
Sheets.Add after:=Sheets(Sheets.Count)
Set ws = ActiveSheet
ws.Name = "Final"
Sheets(1).Range("a1,c1").Copy ws.Range("a1")
lrow = sh.UsedRange.Rows.Count
End If
Next
Set sh = Nothing
Set ws = Nothing
End Sub
Option Base 1
Sub variantarray()
Dim a
MsgBox a(4)
End Sub
Option Base 1
Sub negativetopositive()
Dim a
a = Range("a1:b5")
For r = 1 To Range("a1:b5").Rows.Count
For c = 1 To Range("a1:b5").Columns.Count
End If
Next c
Next r
Range("a1:b5") = a
End Sub
Sub deleterows()
lastrow = ActiveSheet.UsedRange.Rows.Count
If Application.WorksheetFunction.CountA(Rows(ictr)) = 0 Then
Rows(ictr).EntireRow.Delete
End If
Next
End Sub
'Declare a two-dimensional array with 4 rows (for the quarters) and 5 columns (for the
years)
'Quarterly Sales of a company over the past 5 years: Dim sales(1 To 4, 1 To 5) As Long
Sub two_dim_array()
isales(1, 1) = 500
isales(2, 1) = 520
isales(3, 1) = 545
isales(4, 1) = 595
isales(1, 2) = 410
isales(2, 2) = 440
isales(3, 2) = 425
isales(4, 2) = 300
isales(1, 3) = 320
isales(2, 3) = 200
isales(3, 3) = 335
isales(4, 3) = 205
isales(1, 4) = 250
isales(2, 4) = 280
isales(3, 4) = 100
isales(4, 4) = 500
isales(1, 5) = 100
isales(2, 5) = 125
isales(3, 5) = 123
isales(4, 5) = 145
isales(1, 5) = 100
isales(2, 5) = 200
isales(3, 5) = 145
isales(4, 5) = 147
For i = 1 To 4
For n = 1 To 5
Sheet3.Cells(i + 1, n + 1) = isales(i, n)
Next n
Next i
End Sub
Sub arraytwodim()
myarray(0, 0) = 10
myarray(0, 1) = 10
myarray(0, 2) = 10
myarray(0, 3) = 10
myarray(1, 0) = 20
myarray(1, 1) = 20
myarray(1, 2) = 20
myarray(1, 3) = 20
myarray(2, 0) = 30
myarray(2, 1) = 30
myarray(2, 2) = 30
myarray(2, 3) = 30
For i = 0 To 2
For j = 0 To 3
Next j
Next i
End Sub
UFD’s
Advantages:
Disadvantages:
Note: when a UFD is called from a cell in excel, it cannot do structural modifications such as
Cut,copy,format etc..
*UFD’s are viewed under USER DEFINED category in insert function dialog (shift+f5)
Syntax:
Code
[exit function]
Fname=value to return
End function
Private functions are not visible to excel users, and can only be used in the same
module in which they are declared
Parameters: variables defined in () in a UDF in order to store the values passed by the
calling program
1) Sub->functions
2) All input should become parameters
3) The return value must be assigned to the UDF’s name
UDF’s created in a workbook can be used from other workbooks only if the source is open
Store UDF’s in personal Macro wbk in order to use them in all open workbooks
How?
Open vbeditor
Save
Usage:personal.xlsb fname(arguments)
Extract numbers:
End If
Next
extractnumbers = strnum
End Function
Sub callextractnums()
Dim c As Range
c.Next = extractnumbers(c.Value)
Next
End Sub
str = Application.WorksheetFunction.Trim(str)
Dim a
wordcount = UBound(a) + 1
End Function
Function sheetname()
sheetname = ActiveSheet.Name
End Function
Function myorg()
myorg = "informatica.org"
End Function
Function lastrow()
End Function
sc = selectedcell.Column
End Function
'i.e modifications to the argument in the UDF do not affect the actual values in the calling
program
' i.e. modifications to the argument in the UDF do affect the actual values in the calling
program
Sub CallingProcedure()
Dim A As Long
Dim B As Long
A = 123
B = 456
Debug.Print "BEFORE CALL = A: " & CStr(A), "B: " & CStr(B)
Debug.Print "AFTER CALL = A: " & CStr(A), "B: " & CStr(B)
End Sub
X = 321
Y = 654
End Sub
Sub CallHike()
Salary = 10000
End Sub
S = S * 0.25
End Function
Volatile functions:
By default UDF in excel vba are not volatile, they are not recalculated when any of the
function arguments change. A volatile function will be recalculated whenever calculation
occurs in any cell on the worksheet.
Application.Volatile
End Function
Type of Errors:
Compile errors:
Compile errors result from incorrectly constructed code. You may have used property or
method that does not exist on an object, or put in front without a Next or if without an
end if.
When you run code, the complier goes through the code first and checks for these types of
error. If any are found, the code will be run but an error message will be displayed referring
to the first error found. Note that there could be several compile errors in a procedure, but
only first one will be flagged.
Runtime Errors:
These are errors that occur when your program is running,. For example try to open a file
that does not exist these would create an error message and halt execution of the program.
Logical Errors:
Logical errors occur when your application does not perform the way you intended. The
code can be valid and run without producing any errors.
Error message:
Sub test_errors()
temp = Dir("d:\*.*")
Exit Sub
err_handler:
End Sub
Resume statement:
The Resume statement can be added to make the code execution branch back to the
statement where the error occurred. This gives the opportunity for the user to intervene.
Sub Test_Error()
temp = Dir("d:\*.*")
Exit Sub
err_handler:
If err_number = 71 Then
Else
End If
Resume
End Sub
You can also add the statement Next to Resume. This will skip over the statement that
created the error and therefore ignore the error
Userforms:
eg: Button_clik
button:object
click:event(Procedure)
Controls( tool box items with predefined properties & methods) can be placed on userforms.
Double click a control to draw multiple instances of the control on the userform
To create a userform
Insert menu->userforms:
Sub showfrm()
UserForm1.Show
End Sub
Dim ss As Worksheet
Set ss = ThisWorkbook.Sheets("Sheet1")
nr = ss.Cells(Rows.Count, 1).End(xlUp).Row + 1
ss.Cells(nr, 1) = TextBox1.Value
ss.Cells(nr, 2) = TextBox2.Value
ss.Cells(nr, 3) = ComboBox1
End Sub
User form:
Properties window(F4)
Name:userform1
Note:Name property is used to identify an object in code
1) Label:
Displays text
Press F4:
Caption: Text
Aling:left/right/center
Autosize:True/false
Visible:true/false
Others:forecolor,backcolor,height,width etc..
TextBox:
Read/write text
Text:read/write
Maxlength(default 0)
Scrollbars:horizontal/vertical/both/none
Multiline:true/false
Textbox example:
Me.Label1.Caption = Len(TextBox1.Text)
End Sub
Me.TextBox1.MaxLength = 10
End Sub
Cancel = True
End If
End Sub
End Sub
F4:Property window
Name:cmd…
Accelerator: one letter from caption to be used as a shortcut along with ALT
With Me.CommandButton1
.Font.Name = "Verdana"
.ForeColor = vbRed
.Accelerator = "R"
End With
End Sub
Combobox: enables the user to select/type an item from the drop down
Style: fmstyledropdowncombo/list
Sub daily()
MsgBox "daily"
End Sub
Sub weekly()
MsgBox "Weekly"
End Sub
Sub monthly()
MsgBox "Monthly"
End Sub
With ComboBox1
.Style = fmStyleDropDownList
.AddItem "A"
.AddItem "B"
'.list=sheets(1).range("A1:A10").value
End With
End Sub
End Select
End Sub
LIstbox: enables the user to select one/more items from the dropdown
F4:
Selected(index):true/false
With ListBox1
.MultiSelect = fmMultiSelectExtended
.AddItem "A"
.AddItem "B"
End With
End Sub
Dim i As Integer
With ListBox1
For i = 0 To .ListCount - 1
End Select
End If
Next
End With
End Sub
Excel->Sheet(1)
Me.OptionButton1.Value = True
Me.CheckBox1.Value = True
Me.OptionButton3.Value = True
End Sub
Frame1.Visible = True
Else
Frame1.Visible = False
End If
End Sub
Set ws=sheets(1)
Rowcount=ws.usedrange.rows.count
Ws.cells(rowcount+1,”A”)=rowcount
Ws.cells(rowcount+1,”B”)=txtname.text
If optmale.value=true then
Ws.cells(rowcount+1,”C”)=”Male”
Else
Ws.cells(rowcount+1,”C”)=”Female”
End if
If chkeducated.value=true then
If optg.value=true then
Ws.cells(rowcount+1,”D”)=”Graduated”
Ws.cells(rowcount+1,”D”)=”Undergraduate”
Else
Ws.cells(rowcount+1,”D”)=”Post graduate”
End if
Else
Ws.cells(rowcount+1,”D”)=”Un ducated”
End if
Activeworkbook.save
End sub
Sub mail()
With outmail
.to = "Vinodkumar9247@gmail.com"
.cc = ""
.bcc = ""
.body = "Hello Team" & vbNewLine & "Please find the detail" & _
vbNewLine & venewline & vbNewLine & "Regards" & vbNewLine & "Excel Team"
.display
End With
End Sub
Connecting to databases:
You can make your code interact with any databases as long as database is ODBC(Open
database connectivity) compatible and appropriate driver is available
ODBC Links:
You need to first set up an ODBC link to point to the database that you want to work with.
You do this by selecting control panel in windows, then administrative tools, and then data
source(ODBC).
If you do not already have a data source name (DSN) set up for the database.click add this
will give you a listof available database drivers.
Using ADO:
To use ADO in your code, you must first include a reference to object library by selecting
Tools|References from the VBE menu.scroll down until you get to Microsoft library Activex
Data objects 6.0 library
Sub connectdb()
strpath = Sheets("Sheet1").Range("e1").Value
With cnn
.Provider = "Microsoft.ace.oledb.12.0"
.Mode = adModeReadWrite
.Open strpath
End With
End Sub
Sub disconnectdb()
cnn.Close
End Sub
Sub addreacords()
srow = 2
Dim rs As ADODB.Recordset
Call connectdb
With rs
.AddNew
End With
srow = srow + 1
Loop
Range("a2:c50000").ClearContents
Set rs = Nothing
Call disconnectdb
End Sub
Sub connectdb()
strpath = Sheets("Sheet1").Range("e1").Value
With cnn
.Provider = "Microsoft.ace.oledb.12.0"
.Mode = adModeReadWrite
.Open strpath
End With
End Sub
Sub disconnectdb()
cnn.Close
End Sub
Sub retriverecords()
srow = 2
Dim rs As ADODB.Recordset
srow = srow + 1
rs.MoveNext
Loop
Set rs = Nothing
Call disconnectdb
End Sub