Вы находитесь на странице: 1из 91

VBA Notes

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

Enabling Developer Tab:

Excel 2007: office button->excel options->Popular->Show Developer tab in the Ribbon->Ok

Code Group:

Visual Basic Editor (Alt+F11):

Opens vb editor/VBE/VBA IDE

IDE: Integrated development environment

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.

Here macros can be used in all open workbooks by default.

View Macros: alt+F8

Recording Macros:

1. Select a cell.

Any cell will do.

2. Choose Developer  →  Code  →  Record Macro or click the macro recording button on the status bar.

The Record Macro dialog box appears.


The Record Macro dialog box appears when you’re about to record a macro.

3. Enter a name for the macro.

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.

5. Make sure the Store Macro In setting is This Workbook.

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.

8. Type your name in the active cell.

9. Move the cell pointer to the cell below and enter this formula:

=NOW()

The formula displays the current date and time.

10. Select the formula cell, and press Ctrl+C to copy that cell to the Clipboard.
11. Choose Home  →  Clipboard  →  Paste  →  Values (V).

This command converts the formula to its value.

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.

14. Choose Developer  →  Code  →  Stop Recording.

The macro recorder is turned off.

Rules for Naming a Macro:

a) First letter must be an Alphabet


b) No spaces
c) _ is optional
d) Max 255 characters

VBA code & Macro Names are not case sensitive

Store macro in: determines the workbook that saves the macro:

a:This workbook: Active workbooks/current workbook

b:New workbook: A new workbook is created to store the macro

c: personal macro workbook(PMW):An optional, hidden,auto-loaded workbook which is user specific


and is used to store frequently used macros

Name:Personal.xls(b)

b-binary

Application.startuppath property can be used to find the path

thisworkbook.Path

To view personal.xlsb in execution :view tab->unhide->personal->ok

Saving a workbook with macros:

Upto & including excel 2003:.xls

From excel 2007 on wards:.xlsm or .xlsb


(.xlsm:Macro enabled workbook)

Use Relative References: is used to record macros so that they run with references to the active cell

Macro Security

Set a security level:


 Disable all macros without notification: Allows you to run only those macros stored in a trusted location.
Click the Trusted Locations setting in the left pane to manage these trusted locations. Also, since the macros
are automatically disabled, this option disables security alerts.

 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

Select Protection->Lock project for viewing->password and confirm password

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.

Constant Value Description

vbOKOnly 0 Display OK button only.

vbOKCancel 1 Display OK and Cancel buttons.

vbAbortRetryIgnore 2 Display Abort, Retry, and Ignore buttons.

vbYesNoCancel 3 Display Yes, No, and Cancel buttons.

vbYesNo 4 Display Yes and No buttons.


vbRetryCancel 5 Display Retry and Cancel buttons.

vbCritical 16 Display Critical Message icon.

vbQuestion 32 Display Warning Query icon.

vbExclamation 48 Display Warning Message icon.

vbInformation 64 Display Information Message icon.

vbDefaultButton1 0 First button is default.

vbDefaultButton2 256 Second button is default.

vbDefaultButton3 512 Third button is default.

vbDefaultButton4 768 Fourth button is default.

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

vbMsgBoxRight 524288 Text is right aligned

vbMsgBoxRtlReading 1048576 Specifies text should appear as right-to-left reading on Hebrew


and Arabic systems

Constant Value Description

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:

Use view menu to open a window/a component

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)

VBA project can have modules,userforms and class modules

Properties window (F4):displays the properties of the selected item, and enables the user to modify

This window is mainly used while working with user forms

Immediate window:(ctrl+G):runs the current vba statement on pressing enter

Ctrl+enter :new line

Contents are temporary

Eg: print 10+20

?10+20

Code window(F7): to view/writer/change/delete/debug/run code

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:

Ex: sub Testvariabes()

Temp=”david”

Msgbox temp

Temp=8

Msgbox temp

End sug

Return value Type

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

Eg: Dim Myinteger as integer

Numeric Data Types

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

Long data type


A 4-byte integer ranging in value from -2,147,483,648 to 2,147,483,647. The ampersand (&) type-declaration
character represents a Long in Visual Basic.

Sub Numberofrows()

Dim Numberofrows as long

Numberofrows=worksheets(1).rows.count

Msgbox numberofrows

End sub

Currency data type


A data type with a range of -922,337,203,685,477.5808 to 922,337,203,685,477.5807. Use this data type for
calculations involving money and for fixed-point calculations where accuracy is particularly important. The at sign
(@) type-declaration character represents Currency in Visual Basic.

Single data type


A data type that stores single-precision floating-point variables as 32-bit (2-byte) floating-point numbers, ranging in
value from -3.402823E38 to -1.401298E-45 for negative values, and 1.401298E-45 to 3.402823E38 for positive
values. The exclamation point (!) type-declaration character represents a Single in Visual Basic

Sub floats

Dim floatingpoint as single ‘change to double

Floatingpoing =10/3

Msgbox floatingpoint

End sub

Double data type


A data type that holds double-precision floating-point numbers as 64-bit numbers in the range -
1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to
1.79769313486232E308 for positive values. The number sign (#) type-declaration character represents the Double
in Visual Basic.

String data type


A data type consisting of a sequence of contiguous characters that represent the characters themselves rather
than their numeric values. A String can include letters, numbers, spaces, and punctuation. The String data type can
store fixed-length strings ranging in length from 0 to approximately 63K characters

Eg: Dim panid as string*10

Date data type


A data type used to store dates and times as a real number. Date variables are stored as 64-bit (8-byte) numbers.
The value to the left of the decimal represents a date, and the value to the right of the decimal represents a time.

1st Jan 100 to 31st Dec 9999

Object data type


Stores VBA objects, File-System-Objects[Pivot tables,Workbooks, etc…]

Boolean: True/False

Operators:

Arithmetic Operators:

Exponentiation(˄)

Addition and subtraction(+,-)

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)

String concatenation (&)

Comparison

Operator Meaning

< Less than

<= Less than or equal to

> Greater than

>= Greater than or equal to

= Equal to

<> Not 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

Option compare text

Sub text

Msgbox “Richard” like “Richard”

End sub
Functions

MID: Using this function we can split the given string

Syntax: Mid(string,start number,[Length])

Eg: sub split_string()

X=”123excel”

Z=mid(x,4)

Msgbox z

End Sub

Right: to get specific characters from right side

Syntax: Right(String,Number of characters)

Left: to get specific characters from left side

Syntax: Left(string, number of characters)

Ucase: Changes everthing in the string to uppercase:

X=Ucase(“excel”)

LCase: Changes everything in the string to lower case:

X=Lcase(“EXCEL”)

Instr:This function is used to search a string for a specified substring.

Syntax: Instr([start,]string 1,string 2,[compare])

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

->returns the position of string2 in string 1

->returns 0 if string 2 is not found


->is a case sensitive function because the default option is vbbinarycompare

?instr(1,"teoracle corporate floor","or",vbBinaryCompare)

?instr(1,"oracle","RA",vbTextCompare)

Ltrim:it removes the left most spaces

?ltrim(“ abc pvt ltd”):abc pvt ltd

?Rtrim:removes right most spaces

?rtrim(“abc pvt ltd “) ans:abc pvt ltd

‘Calling an excel function from VBA

?application.worksheetfunction.trim(“ abc pvt ltd”)

Abc pvt ltd

Replace: Replace(string,find,replace)

->case sensitive

?replace("Jack & Jue","J","Bl",compare:=vbTextCompare)

Isnumeric:it will return whether the value is numeric or not

?Isnumeric(“123”)

True

?isnumeric(“a123’)

False

?val(“a123”)

?val(“123”):It converts string to value

123

Isdate: it checks give value is date or not


?isdate(“29-feb-2016”)

True

?isdate(“29-feb-2017”)

False

?now(): The now function returns the current date and time

6/11/2016 8:16:17 PM

?date():Date returns the current date

6/11/2016

?Time():The time function return the current system time

DateAdd: DateAdd allows the addition and subtraction of a specified time interval to a date.

Syntax: DateAdd(interval,Number,date)

Time period Interval

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”)

Datepart:The Datepart function returns a specified part of a given date

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:it returns an integer between 1 and 12 based on the date expression

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:it will returns the day of a give weekday number

?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

?Time$()->(24 hrs 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”)

?hour("16-Mar-2016 4:30 pm")

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:

Excel Object Model: The internal structure of excel through which vba programs can operate excel
objects

Application:Excel

Workbooks: A collection of all open workbooks

Workbooks(Index/name): Specific workbook

Activeworkbook: current workbook

Sheets: All sheets in a workbook

Sheets(Index/Name):specific sheet

Range: a collection of one/more cells

Activecell: current cell

Cells(rowindex,columnindex):Specific cell

Method: it is an action against an object

Eg: Cut,copy,delete etc..

Note: . Symbol is used to access properties/Method of an object

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

‘Activate method is used to a change activecell (without the selection)

‘or to select another area

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.ClearContents 'Only data

Cells.Clear 'all

Cells.ClearComments

Cells.ClearFormats

End Sub

Sub cutmethod1() 'paste

'Within the activesheet

'Syntax: rage.Cut Destination

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

'Activate method is used to change the active cell(without the seletion0

'or to select another area

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

Range("a5:a10") = "sample text”

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.ClearContents 'only data

Cells.Clear 'All

Cells.ClearComments

Cells.ClearFormats

End Sub

Sub cutmethod1()

'within the activesheet

'Syntax: range.cut destination

Range("a1:a10").Cut Range("c1")

End Sub

Sub cutmethod2()

'between 2 sheets in the activeworkbook

'Syntax: range.cut destination

Sheets("Sheet1").Range("a1:a10").Cut Sheets("Sheet2").Range("c1")

Sheets("Sheet2").Activate

End Sub

Sub cutmethod3()

'between 2 sheets in 2 workbooks

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

Sub copymethod() ’pastespecial

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

'removes the data from clipboard

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

Inputbox: Inputbox is a built in function to read a values

Syntax:inputbox(Prompt,[title],[default])

Deafult:an optional suggested values

Sub readvaluesfromuser()

Dim a As Integer, b As Integer

a = InputBox("enter a values", "a value")

b = InputBox("enter b value", "b value")

MsgBox "the result is " & a + b

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

‘with speedup the process

Sub withex()

Dim a As Integer, b As Integer

With Sheets("Sheet1")

a = .Range("a1")

b = .Range("b1")
.Range("c1") = "The result is " & a + b

End With

End Sub

Conditional Statements

If and Select case

IIF:built in function (Inline if)

Syntax:

Iif(expression,true part,false part)

->it validates an expression and runs either TRUE or FALSE part

Sub iifex()

Dim a As Integer

Dim b As Integer

a = 10: b = 20

MsgBox IIf(a < b, "Yes", "No")

End Sub

Sub iffex2()

'leap check

Dim y As Integer

y = Range("a1")

Range("a2") = IIf(y Mod 4 = 0, "Leap Year", "Not a leap year")

End Sub

Sub usernamepwdcheck()

Dim uname As String, pwd As String

uname = InputBox("Enter username")

pwd = InputBox("enter password")


Range("c1") = IIf(uname = Range("a1") And pwd = Range("b1"), "Yes", "No")

End Sub

Note: iff cannot check multiple expressions

Sub usernamepwdcheck()

Dim uname As String, pwd As String

uname = UCase(InputBox("Enter username"))

pwd = UCase(InputBox("enter password"))

Range("c1") = IIf(uname = Range("a1") And pwd = Range("b1"), "Yes", "No")

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

Elseif condition2 then

Code

Elseif condition3 then

Code

---

--

[else code]

End if
Note: IF Statement is written in a single line, end if is not required

A single line if cannot contains elseif code

Syntax: if condition then code else code

Sub calculatecommission()

Dim salesamount As Double

Dim commission As Double

salesamount = Range("a1")

If salesamount >= 100000 Then commission = salesamount * 0.5 Else commission = 1000

Range("a2") = Round(commission, 2)

End Sub

Sub results()

Dim score As Integer, result As String

score = Range("a1").Value

If score >= 60 Then result = "pass" Else result = "fail"

Range("b1").Value = result

End Sub

Sub results()

Dim score As Integer, result As String

score = Range("a1").Value

If score >= 60 Then result = "pass" Else result = "fail"

Range("b1").Value = result

End Sub
Sub calculatecommissionmulti()

Dim salesamount As Double, commission As Double

salesamount = Range("a1")

If salesamount >= 10000 Then

commission = salesamount * 0.5

Else

commission = 1000

End If

Range("a2") = Round(commission, 2)

End Sub

Sub calculatecommissionelseif()

Dim salesamount As Double

Dim commission As Double

salesamount = Range("a1")

If salesamount >= 100000 Then

commission = salesamount * 0.5

ElseIf salesamount >= 700000 Then

commission = salesamount * 0.25

Else

commission = 1000

End If

Range("b1") = Round(commission, 2)

End Sub

Singleline: No elseif & No end if


Multiline: elseif & end if can be used

Nestedif: Using one/more if block inside an IF block

Sub Nestedif()

Dim m1 As Integer, m2 As Integer, m3 As Integer

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

Dim result As String

If m1 >= 40 And m2 >= 40 And m3 >= 40 Then

If avg >= 60 Then

result = "A"

ElseIf avg >= 50 Then

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

lastrow = Sheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row

For i = 2 To lastrow

b = Range("a" & i)

a = WorksheetFunction.Match(b, Range("g2:g5"), 0)

If a > 0 Then

Range("h" & i).Copy

Range("a" & i).PasteSpecial xlPasteAll

End If

Next

Application.CutCopyMode = False

End Sub

Sub Markscheck()

Dim sngmarks As Single

sngmarks = 60

If sngmarks >= 80 Then

MsgBox "Excellent"

ElseIf sngmarks >= 60 Then

MsgBox "Good"

ElseIf sngmarks >= 40 Then

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

Syntax: select case varname/expression

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

Case 1: MsgBox "Sunday"

Case 2: MsgBox "Monday"

Case 3: MsgBox "Tuesday"

Case 4: MsgBox "Wednesday"

Case 5: MsgBox "Thursday"

Case 6: MsgBox "Friday"

Case 7: MsgBox "Saturday"

Case Else: MsgBox "Invalid no"

End Select

End Sub
Sub pantype()

Dim panid As String * 10, pantype As String

panid = Range("a1")

Select Case UCase(Mid(panid, 4, 1))

Case "P": pantype = "Person"

Case "M": pantype = "Minor"

Case "H": pantype = "H.U.F"

Case "C": pantype = "Company"

Case "S": pantype = "Society"

Case "B": pantype = "Bank"

Case "T": pantype = "Trust"

Case Else: pantype = "Wrong panid"

End Select

Range("b1") = pantype

End Sub

Sub getconfhall()

Dim deptno As Integer, confhall As String

deptno = Range("a1")

Select Case deptno

Case 1 To 10, 12, 34, 97: confhall = "A"

Case 11, 23, 65 To 90, 25: confhall = "B"

Case Is <= 100: confhall = "C"

Case Else: confhall = "wrong deptno"


End Select

Range("b1") = confhall

End Sub

Sub scorecheck()

Dim score As Integer, result As String

score = Range("a1")

Select Case score

Case Is >= 80

result = "Very good"

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.

Syntax: For counter= start value to end value [Step increment]

{…statements..}

Next counter

Counter: variable Name

Start: the starting value for counter


End: the ending value for 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()

Dim strnumber As Integer

Dim endnumber As Integer

endnumber = 5

For strnumber = 1 To endnumber

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()

Dim loopcount As Integer

For loopcount = 1 To 10

Debug.Print "Loopcounter=" & loopcount

Next loopcount
End Sub

Sub forex5()

'print 1 to 10 in column A in sheet1

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()

'print 10 numbers per column

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()

'Def:A no divisible by one & itself

'eg: 2,3,5,7,11,13....

Dim n As Integer, i As Integer, zerocount As Integer

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

Range("a2") = "Not a prime"

End If

End Sub

Sub print2ndmulti()

Dim i As Integer

Cells.Clear

For i = 1 To 10

Cells(i, "a") = 2 & "x" & i & "=" & 2 * i

Next i
End Sub

Sub printnthtable()

Dim i As Integer

n = InputBox("Enter a number")

Cells.Clear

For i = 1 To 10

Cells(i, "a") = n & "x" & i & "=" & n * i

Next i

End Sub

Sub protectworksheets()

Dim loopcounter As Integer

Dim numberofworksheets As Integer

numberofworksheets = Worksheets.Count

For loopcounter = 1 To numberofworksheets

Worksheets(loopcounter).Protect

'Worksheets(loopcounter).Unprotect

Next loopcounter

End Sub

Sub workbooksclose()

Dim loopcounter As Integer

Dim Numofbooks As Integer

Numofbooks = Workbooks.Count

For loopcounter = 2 To Numofbooks

Workbooks(loopcounter).Close
Next loopcounter

End Sub

Sub FortnightDates()

Dim lastrow As Integer

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

a = WorksheetFunction.Match(Range("a" & i), Range("e1:e5"), 0)

If a > 0 Then

Range("f" & a).Copy

Range("a" & i).PasteSpecial xlPasteAll

End If

Next
Application.CutCopyMode = False

End Sub

Nested Loops:

One Loop may contain one/more loops of any type in it

Note: for each cycle in OUTER LOOP, all cycles of INNER LOOPS are executed

Sub print1to20Mtables()

Dim n As Integer, i As Integer

Cells.Clear

For n = 1 To 20 'Outer

For i = 1 To 20 'inner

Cells(i, n) = n & "x" & i & "=" & n * i

Next i

Next n

Columns.AutoFit

End Sub

Sub listofprimenosbetween1to100()

Dim n As Integer, i As Integer, zerocount As Integer, rno As Integer

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()

For i = 1 To 5 'for rows

For j = 1 To i 'for columns

Cells(i, j).Value = "*"

Next j

Next i

End Sub

Sub pyramid1()

For i = 1 To 5 'for rows

For j = 1 To i 'for columns

Cells(i, 5 + j).Value = "*"

Cells(i, 6 - j).Value = "*"

Next j

Next i

End Sub

For each loop

This loop is used to loop through objects such as workbooks,sheets,cells,ranges etc..


Syntax: For Each Vaiable_Name in collection_name

Next variable_Name

Note: SET keyword must be used while assigning/removing a reference to/from an object variable

Note: set obectvariable=Nothing ‘To clear the memory

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

Dim sh As Worksheet, i As Integer

Cells.Clear

For Each sh In Sheets 'is a collection of all sheets in a current workbook

i=i+1

Cells(i, "a") = sh.Name

Next

'count is common property of collections

Cells(i + 1, "a") = "No of sheets" & Sheets.Count

Columns.AutoFit

Set sh = Nothing
End Sub

Sub getlistofopenworkbooks()

Dim wb As Workbook, i As Integer

Cells.Clear

For Each wb In Workbooks 'is a collection

i=i+1

Cells(i, "a") = wb.Name

Cells(i, "b") = wb.FullName

Cells(i, "c") = wb.Path

Next

Cells(i + 1, "a") = "No of workbooks" & Workbooks.Count

Columns.AutoFit

Set wb = Nothing

End Sub

Sub loopthrougranges()

Dim c As Range

For Each c In Range("a1:a10")

Debug.Print c.Address

Debug.Print c.Value

Next

Set c = Nothing

End Sub
Sub Extractnumbers()

Dim num As String

Dim str As String

lastrow = Cells(Rows.Count, 1).End(xlUp).Row

For j = 1 To lastrow 'pickup rows

num = ""

str = Range("a" & j).Value

For i = 1 To lastrow

If IsNumeric(Mid(str, i, 1)) Then 'check row values

num = num & Mid(str, i, 1)

End If

Next i

Range("b" & j) = num

Next j

End Sub

Color index:

Default color:56

Property: Colorindex

Custom colors:16M

Property:color

To identify te background color of a cell:

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

Range("a" & i).Interior.ColorIndex = i

Next

End Sub

Sub regeg()

Range("d1").Interior.Color = RGB(240, 30, 245)

End Sub

Sub fontcolurs()

Range("e1").Font.ColorIndex = 3

Range("f1").Font.Color = 16077040

End Sub

Usedrange:A range that identifies all cells used in a sheet

It is like a box selection

The default address:$A$1

?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()

Dim lrow As Long

lrow = ActiveSheet.UsedRange.Rows.Count

Dim r As Long

For r = lrow To 1 Step -1

If Application.WorksheetFunction.CountA(Rows(r)) = 0 Then

Rows(r).Delete

End If

Next

End Sub

Sub selectcellsdiagonally()

Dim n As Integer, str As String

n = InputBox("enter no.of cells")

Dim i As Integer

For i = 1 To n

' If Len(str) > 0 Then

str = str & "," & Cells(i, i).Address(False, False)

Else

str = Cells(i, i).Address(False, False)

' End If

Next
Range(str).Select

End Sub

Sub Repeatvalues()

'Repeat entries of col A in Col C

'based on values of col B

Dim c As Range, rpt As Integer, i As Integer, rowno As Integer

For Each c In Range("a1:a3")

rpt = c.Next.Value

For i = 1 To rpt

Cells(rowno + i, 3) = c.Value

Next

rowno = rowno + rpt

Next

Set c = Nothing

End Sub

Sub namecheck()

Dim c As Range

Dim fndvalue As String

For Each c In Range("a1:a5")

If c.Value = "Ram" Then

'c.Next.Value = "Found"

c.Offset(0, 1) = "Found"

End If

Next
Set c = Nothing

End Sub

While …Wend Loop:

It is condition based, i..e. it runs as long as the condition is TRUE

It is a pre-check loop, i..e. it checks the condition before each cycle

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

Loop while condition or Loop until condition

Sub dowhileloop()

x=2
Do While Cells(x, 2) <> ""

Cells(x, 3).Value = Cells(x, 2).Value * 0.4

Cells(x, 4).Value = Cells(x, 3).Value + Cells(x, 2).Value

x=x+1

Loop

End Sub

Sub calcommission()

'for an unknown no of salesman

Dim samt As Double, comm As Double

Dim choice As Integer

Do

samt = InputBox("Enter amount")

If samt >= 100000 Then

comm = Round(samt * 0.5, 2)

Else

comm = 1000

End If

choice = MsgBox("Sales amount" & samt & vbNewLine & "commisso" & comm & vbNewLine & "Do
u want to continue?", vbYesNo)

Loop While choice = vbYes

'Loop Until choice = vbNo

End Sub
GOTO: Change the flow of the program

Syntax: Goto _line_

The required line argument can be any line label or number

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

'Stops displying exel warning message

On Error Resume Next

'it ignores all errors& continues next code

For Each sh In Sheets

If IsEmpty(sh.UsedRange) = True Then

sh.Delete

End If

Next sh

On Error GoTo 0 'stop

0: MsgBox "Task completed"


Application.DisplayAlerts = True

'reset

End Sub

VBA Methods to Find the Last Cell,Row, or Coumn

Method 1:

Range.End

-No Blank cells

-Single Row or Column

Sub Find_last_row_column()

'Range("A" & Rows.Count).End(xlUp).Select

'Cells(1, Columns.Count).End(xlToLeft).Select

End Sub

Sub s2()

a = Range("A" & Rows.Count).End(xlUp).Row

b = Cells(1, Columns.Count).End(xlToLeft).Column

MsgBox a & "," & b

End Sub

Method 2:

Range.Find

-Blanks Ok

-Searches Entire Ranges/Sheet

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()

Dim lrow As Long

lrow = Cells.Find(What:="*", _

lookat:=xlPart, _

LookIn:=xlFormulas, _

searchorder:=xlByRows, _

searchdirection:=xlPrevious, _

MatchCase:=False).Row

MsgBox "lastrow is" & lrow

End Sub

Method 3:

Range.Specialcells

-Find last used cell

-Helps Remove unused cells

Ctrl+End

Sub range_specialcells()

MsgBox Range("a1").SpecialCells(xlCellTypeLastCell).Address

End Sub

Different ways to Vlookp

Sub Myloopup1()

Dim emp_name As String


Dim salary As Long

emp_name = "Noah"

Set myrange = Range("a:b")

salary = Application.WorksheetFunction.VLookup(emp_name, myrange, 2, False)

MsgBox emp_name & "'s salary is " & salary

End Sub

Sub Myloopup2()

On Error GoTo MyerrorHandler

Dim emp_name As String

Dim salary As Long

emp_name = InputBox("Please enter employee's name")

If Len(emp_name) > 0 Then

Set myrange = Range("a:b")

salary = Application.WorksheetFunction.VLookup(emp_name, myrange, 2, False)

MsgBox emp_name & "'s salary is & salary"

Else

MsgBox "You didn't enter any name!"

End If

Exit Sub

MyerrorHandler:

If Err.Number = 1004 Then

MsgBox "Employee name not in the data!"

End If
End Sub

Sub mylookup3()

Dim lastrow As Long

lastrow = Sheet1.Range("a" & Rows.Count).End(xlUp).Row

Set myrange = Range("a:b")

For i = 2 To lastrow

Cells(i, 3) = Application.WorksheetFunction.VLookup(Cells(i, 1), myrange, 2, False)

Cells(i, 3) = Cells(i, 3) + Cells(i, 3) * 0.3

Next i

End Sub

Working with other applications:

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

Eg: word library

->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

->same library is required on target machine

->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”)

->variables are generic type(...as object)

->Runs with any compatible library

->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

W.Selection.TypeText "sample text"

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 W As New Word.Application

Dim d As Word.Document

W.Visible = True

Set d = W.Documents.Add

W.Selection.TypeText "sample text"

d.SaveAs "C:\Users\Welcome\Desktop\test.docx"
d.Close

W.Quit

Set d = Nothing

Set W = Nothing

End Sub

Windows file system

Includes Drivers,Sub folders & files

Early Binding:Tools->References->Microsoft scripting runtime

Late Binding: createobject(“Scripting.Filesystemobject”)

Object Browser(F2):Displays all libraries, clases, objects,methods,properties & constants

Sub driverex()

Dim fs As Object

Set fs = CreateObject("Scripting.Filesystemobject")

'Now fs refers to windows file system

Dim d, i As Integer

For Each d In fs.Drives 'is a collection

i=i+1

Cells(i, 1) = d

Next

Set d = Nothing

Set fs = Nothing

End Sub

Sub Listoffoldersfromselectedfolder()

Dim folpath As String

folpath = InputBox("Enter path")


Dim fs, fol

Set fs = CreateObject("Scripting.Filesystemobject")

Set fol = fs.GetFolder(folpath)

Dim d, i As Integer

Cells.Clear

For Each d In fol.SubFolders

i=i+1

Cells(i, 1) = d.Name

Next

Set d = Nothing

Set fs = Nothing

End Sub

Sub listoffileswithaattribuesfromselectedfolder()

Dim folpath As String

folpath = InputBox("Enter path")

Dim fs, fol

Set fs = CreateObject("Scripting.Filesystemobject")

Set fol = fs.GetFolder(folpath)

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, 5) = "Date created"

Cells(i, 6) = "Date last modified"

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

Sub getselectedfolder() 'single folder

Dim folpath As String

With Application.FileDialog(msoFileDialogFolderPicker)

.Title = "Select the source folder"

.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

For Each f In .SelectedItems

i=i+1

Cells(i, 1) = Mid(f, InStrRev(f, "\") + 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.

File Dialog filters:

Restrict the user to select specific type of files

Sub filters()

With Application.FileDialog(msoFileDialogFilePicker)

.AllowMultiSelect = False 'one file

.filters.Clear 'remove all files option

'syntax:filters.add descritpion.extensions

.filters.Add "Workbooks", "*.xls;*.xlsx;*.xlsm"

.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

Create a new books

Workbooks.add

Sub DeleteBlankSheetsFromallFiles()

'in selected folder

Dim folpath As String

folpath = InputBox("folderpath")

Dim fs, fol, f

Set fs = CreateObject("Scripting.Filesystemobject")

Set fol = fs.getfolder(folpath)

On Error Resume Next

Dim sh As Worksheet

Application.DisplayAlerts = False4

For Each f In fol.Files

If UCase(fs.GetextensionName(f.Name)) = "XLSX" Then

Workbooks.Open f.Path

For Each sh In Sheets

If IsEmpty(sh.UsedRange) = True Then

sh.Delete

End If
Next sh

ActiveWorkbook.Save

ActiveWorkbook.Close

End If

Next f

End Sub

'working with text files

Sub CreateTextFileEx()

'syntax: create textfile(filename)

Dim fs, f as object

Set fs = CreateObject("Scripting.Filesystemobject")

Set f = fs.createtextfile("C:\Users\Welcome\Desktop\sample.txt")

'Writeline: writes a line into a text file

f.writeline "Sample text"

f.writeline "By excel"

Set f = Nothing

Set fs = Nothing

End Sub
Sub Overwritetextfile()

'Syntax: open text file(filename,[mode])

'mode: 1-Read,2-[over] write,8-Append(add to the existing)

Dim fs, f As Object

Set fs = CreateObject("Scripting.Filesystemobject")

Set f = fs.opentextfile("C:\Users\Welcome\Desktop\Intent login.txt", 2)

f.writeline "one"

f.writeline "two"

Set fs = Nothing

Set f = Nothing

End Sub

Sub writeallcommentsfromcurrentsheetintoatextfile()

Dim fs, f As Object

Set fs = CreateObject("Scripting.Filesystemobject")

Set f = fs.createtextfile("C:\Users\Welcome\Desktop\ssss.txt")

Dim c As Range

For Each c In Sheets("Sheet1").UsedRange.SpecialCells(xlCellTypeComments)

f.writeline c.Address

f.writeline c.Comment.Text

Next c

Set f = Nothing

Set fs = Nothing

End Sub
Sub wordcountext()

Dim wcount As Integer, str As String, i As Integer

str = Application.WorksheetFunction.Trim(Range("a1"))

If Len(str) > 0 Then

wcount = 1

End If

For i = 1 To Len(str)

If Mid(str, i, 1) = " " Then

wcount = wcount + 1

End If

Next

Range("b1") = "No of words " & wcount

End Sub

Arrays

An array is a group of variables with the same data type and name.

Arrays are like collections of variables

An array can store one/more values

Arrays can store data in adjacent memory locations

Arrays can faster than ranges

An array can be static i.e. fixed in size

Or

Dynamic i.e, adjustable in size

An array can be single/double/multidimensional

Single: one column(a list of cricketers)

Two: Multiple columns(a table of details of cricketers)

Multi: collections of single/two dimensional arrays


Note: an array can have 60 dimensions.

Syntax:

Dim variablename(dimensions) as datatype

Sample declarations:

Single:

Dim players(1 to 11) as string

Note:1->lowerbound

Note:11->upperbound

Note:Lbound and Ubound functions are used to find out lowerbond and upperbound of
arrays

Two dimensions:

Dim players(1 to 11,1 to 5) as string

Note: each dim has it own Lbound and Ubound

Multi dimensions:

Dim players(1 to 4,1to 11, 1 to 5) as string

Dim payers(1 to 11) as string ‘explict decalartion i.e, with lowerbound

Dim players(11) as sting ‘Implict declaration i.e, without lowerbound

Note: The default lowerbound of implicit arrays is 0

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

Syntax: option base 0 or 1

Option Base 1

Sub sss()

Dim a(3) As Integer

a(1) = 10

a(2) = 20
a(3) = 30

MsgBox LBound(a)

MsgBox UBound(a)

End Sub

Read the values from excel to array and applying total

Option Base 1

Sub array2()

Dim a(5) As Integer

Dim i As Integer

'read data into the array from excel

For i = LBound(a) To UBound(a) Option Base 1

a(i) = Cells(i, "a")

Next

'process the data

Dim tot As Integer

For i = LBound(a) To UBound(a)

tot = tot + a(i)

Next

'send the data

Range("a6") = tot

End Sub
Sub swapex1()

Dim a As Integer, b As Integer

a = 10

b=3

Dim tempval As Integer

tempval = a

a=b

b = tempval

MsgBox a

MsgBox b

End Sub

Sub swapex2()

Dim a As Integer, b As Integer

a = 10

b=3

a = a + b '13

b = a - b '10

a=a-b '13-10=3

MsgBox a

MsgBox b

Sort the values using arrays

Sub arraystatic() 'sort

Dim a(5) As Integer, i As Integer, tempval As Integer


‘read data into the array from excel

For i = LBound(a) To UBound(a)

a(i) = Cells(i, "a")

Next

For i = LBound(a) To UBound(a)

For j = LBound(a) To UBound(a)

If a(i) > a(j) Then

tempval = a(i)

a(i) = a(j)

a(j) = tempval

End If

Next j

Next i

'send the data to excel

For i = LBound(a) To UBound(a)

Cells(i, "a") = a(i)

Next

End Sub

‘Sorting using array

Option Base 1

Sub arrydynamically()

'Dynamic arrays:

'Arrays that can be adjustable in size


'A dynamic array has no intial size

Dim a() As Integer, i As Integer

''a' is a dynamic array

'Redim statement is used to change the size of a dynamic array

'Syntax: Redim [preserve] variablename(dimension)

'*preserve keyword is used to keep the existing values

'while resizing the arrys

ReDim a(Range("a1").End(xlDown).Row)

End Sub

Consolidate first and last columns

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")

Dim sh As Worksheet, lrow As Long

For Each sh In Sheets

If sh.Name <> "Final" Then

lrow = sh.UsedRange.Rows.Count

sh.Range("a2:a" & lrow & "," & "c2:c" & lrow).Copy _

ws.Range("a" & ws.UsedRange.Rows.Count + 1)

End If

Next

Set sh = Nothing
Set ws = Nothing

End Sub

Option Base 1

Sub variantarray()

Dim a

a = Array(100, "JAMES", "Manager", #7/16/2016#)

'now a is an array of 4 elements

MsgBox a(4)

End Sub

Option Base 1

Sub negativetopositive()

'2 dimensional array

Dim a

a = Range("a1:b5")

'now a is 2-dim array

'the default lbound of all dimensiona is 1

'fist element :a(1,1)

Dim r As Integer, c As Integer

For r = 1 To Range("a1:b5").Rows.Count

For c = 1 To Range("a1:b5").Columns.Count

If a(r, c) < 0 Then

a(r, c) = Abs(a(r, c))

End If
Next c

Next r

Range("a1:b5") = a

End Sub

Sub deleterows()

Dim ictr As Integer

Dim rng As Range

lastrow = ActiveSheet.UsedRange.Rows.Count

For ictr = lastrow To 1 Step -1

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()

Dim i As Integer, n As Integer

Dim isales(1 To 4, 1 To 5) As Integer '4 rows and 5 columns

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

querter 2010 2011 2012 2013 2014


querter
1 500 410 320 250 100
querter
2 520 440 200 280 200
querter
3 545 425 335 100 145
querter
4 595 300 205 500 147

Sub arraytwodim()

Dim myarray(2, 3) As Integer

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

Cells(i + 1, j + 1).Value = myarray(i, j)

Next j

Next i

End Sub

User defined functions:

UFD’s

Advantages:

1) Modularity (splitting into small parts)


2) Reusability

Disadvantages:

Too many UFD’s may degrade the performance

 UFD’s can be called from other programs (sub/functions)


 UFD’s can also be called from a cell in excel

Note: when a UFD is called from a cell in excel, it cannot do structural modifications such as

Cut,copy,format etc..

*UFD’s must be written in modules

*UFD’s are viewed under USER DEFINED category in insert function dialog (shift+f5)
Syntax:

[private/public] function fname([parameters]) as return type

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

Rules to convert a sub into functions:

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?

Record a macro by selecting personal macro wbk option

Open vbeditor

Expand PMW in project explorer->module1->write/paste code

Save

Usage:personal.xlsb fname(arguments)

Userdefined needs to be selected under most recently used

Extract numbers:

Function extractnumbers(str As String)

'now str is a parameters

Dim i As Integer, strnum As String


For i = 1 To Len(str)

If Mid(str, i, 1) Like "[0-9]" Then

strnum = strnum & Mid(str, i, 1)

End If

Next

extractnumbers = strnum

End Function

'Calling a UDF from a sub

Sub callextractnums()

Dim c As Range

For Each c In Range("a1:a3")

c.Next = extractnumbers(c.Value)

Next

End Sub

Function wordcount(str As String)

str = Application.WorksheetFunction.Trim(str)

Dim a

a = Split(str, " ")

wordcount = UBound(a) + 1

End Function

'Functions without parameters

Function sheetname()

sheetname = ActiveSheet.Name

End Function
Function myorg()

myorg = "informatica.org"

End Function

Function lastrow()

lastrow = Cells(Rows.Count, 1).End(xlUp).Row

End Function

Function lastrowc(selectedcell As Range)

'this gives lastrow of selected cell or column

sc = selectedcell.Column

lastrowc = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row

End Function

'call by Value : The value of the Argument is considered

'i.e modifications to the argument in the UDF do not affect the actual values in the calling
program

' Key word: ByVal

'Call by Reference: The Reference(memory) of the argument is considered

' 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)

CalledProcedure X:=A, Y:=B

Debug.Print "AFTER CALL = A: " & CStr(A), "B: " & CStr(B)

End Sub

Sub CalledProcedure(ByRef X As Long, ByVal Y As Long)

X = 321

Y = 654

End Sub

Sub CallHike()

Dim Salary As Double

Salary = 10000

MsgBox "Revised Salary" & Salary + Hike(Salary)

End Sub

Function Hike(ByRef S As Double)

S = S * 0.25

Hike = S ' By Val

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.

Function myfunction(cell As Range)

Application.Volatile

myfunction = cell.Value + cell.Offset(1, 0).Value

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()

On Error GoTo err_handler

temp = Dir("d:\*.*")

Exit Sub

err_handler:

MsgBox "Error message" & " " & Err.Description

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()

On Error GoTo err_handler

temp = Dir("d:\*.*")

Exit Sub

err_handler:

If err_number = 71 Then

MsgBox "The D drive is not ready"

Else

MsgBox "An error occurred"

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:

Creating screens for the end users.

Userforms are used to create rich & user friendly interfaces

Userforms support graphical user interface(GUI)

Programming with event-driven programming

i.e, executing code when an objects event is fired

eg: Button_clik

button:object

click:event(Procedure)

By default, code created for a userform/its objects is private

Controls( tool box items with predefined properties & methods) can be placed on userforms.

The size of userforms or properties can be changed using properties window(F4)

The properties of controls can also be changed using properties window


Format menu options can be used to change the size, the spacing & the alignment of
controls

Double click a control to draw multiple instances of the control on the userform

Userforms can call macros & vice versa

To create a userform

Insert menu->userforms:

Sub showfrm()

'calling a userform through a macro

UserForm1.Show

End Sub

To Add additional controls

Microsoft Data & Time picker control 6.0 (SP)

Private Sub CommandButton1_Click()

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

This property cannot be changed in code

Caption: text in title bar

Others: font,forecolor,backcolor,picture etc..

1) Label:
Displays text

Press F4:

Caption: Text

Aling:left/right/center

Autosize:True/false

Visible:true/false

Others:forecolor,backcolor,height,width etc..

Note:To write code,double click any control/right click

->view code/the userform(f7)

TextBox:

Read/write text

Text:read/write

Maxlength(default 0)

Password char:default none

Scrollbars:horizontal/vertical/both/none

Multiline:true/false

Note:use ctrl+enter to enter next line

Tabindex:tab order to reach the control

Textbox example:

Private Sub TextBox1_Change()

Me.Label1.Caption = Len(TextBox1.Text)
End Sub

Private Sub UserForm_Initialize() 'loading

Me.TextBox1.MaxLength = 10

End Sub

‘Only numeric data

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)

If IsNumeric(TextBox1.Text) = False Then

MsgBox "Please enter numeric values"

Cancel = True

End If

End Sub

‘Add values using text boxes

Private Sub TextBox2_Exit(ByVal Cancel As MSForms.ReturnBoolean)

TextBox3.Text = Val(TextBox1.Text) + Val(TextBox2.Text)

End Sub

Command Button: runs code on click

F4:Property window

Name:cmd…

Caption : text on the button

Accelerator: one letter from caption to be used as a shortcut along with ALT

Control tip text: hint on mouse-enter

Private Sub UserForm_Initialize() ‘loading

With Me.CommandButton1

.Caption = "Run code"

.Font.Name = "Verdana"
.ForeColor = vbRed

.Accelerator = "R"

.ControlTipText = "Click this button to run code"

End With

End Sub

Combobox: enables the user to select/type an item from the drop down

Text: selected item

Style: fmstyledropdowncombo/list

Properties & methods in code:

Listcount: No of items in the list

Additem: <string>:adds to the list

Removeitem:<index>:removes an item from the list

Sub daily()

MsgBox "daily"

End Sub

Sub weekly()

MsgBox "Weekly"

End Sub

Sub monthly()

MsgBox "Monthly"

End Sub

Private Sub UserForm_Initialize()

With ComboBox1

.Style = fmStyleDropDownList
.AddItem "A"

.AddItem "B"

.List = Array("Daily", "Weekly", "Monthly")

'.list=sheets(1).range("A1:A10").value

End With

End Sub

Private Sub CommandButton1_Click()

Select Case ComboBox1.Text

Case "Daily": Call daily

Case "Weekly": Call weekly

Case "Monthly": Call monthly

End Select

End Sub

LIstbox: enables the user to select one/more items from the dropdown

F4:

Multiselect:single/multi(click)/extended(shift/ctrl and click)

Properties & Methods in code:

Selected(index):true/false

Litscount:no of items in the list

Add item<string>:add to the list

Remove item<index>:removes an item from list

Private Sub UserForm_Initialize()

With ListBox1

.MultiSelect = fmMultiSelectExtended
.AddItem "A"

.AddItem "B"

.List = Array("Daily", "Weekly", "Monthly")

End With

End Sub

Private Sub CommandButton1_Click()

Dim i As Integer

With ListBox1

For i = 0 To .ListCount - 1

If Selected(i) = True Then

Select Case .List(i)

Case "Daily": Call daily

Case "Weekly": Call weekly

Case "Monthly": Call monthly

End Select

End If

Next

End With

End Sub
Excel->Sheet(1)

Sno name gender qualification

Optionbutton: to select one among a group of options

Checkbox: to select/deselect an individual item

Frame:works like a container for other controls

Note: A frame control is used to create different groups of optionbuttons

Private Sub UserForm_Initialize()

Me.OptionButton1.Value = True

Me.CheckBox1.Value = True

Me.OptionButton3.Value = True
End Sub

Private Sub CheckBox1_Click()

If CheckBox1.Value = True Then

Frame1.Visible = True

Else

Frame1.Visible = False

End If

End Sub

Private sub cmdsave_click()

Dim ws as worksheet,rowcount as long

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”

Elseif optug.value=true then

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

Outlook using vba:

Sub mail()

Set outapp = CreateObject("Outlook.Application")

Set outmail = outapp.createitem(0)

With outmail

.to = "Vinodkumar9247@gmail.com"

.cc = ""

.bcc = ""

.Subject = "test mail"

.body = "Hello Team" & vbNewLine & "Please find the detail" & _

vbNewLine & venewline & vbNewLine & "Regards" & vbNewLine & "Excel Team"

.display

End With

End Sub

If you want to add attachments:

Type: attachments. add(“path”)

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:

Activex Data Objects(ADO) is the Microsoft technology for connecting to databases.

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

Public cnn As ADODB.Connection

Dim r As Integer, c As Integer

Sub connectdb()

Dim strpath As String

Set cnn = New ADODB.Connection

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

Set cnn = Nothing

End Sub
Sub addreacords()

Dim srow As Long

srow = 2

Dim rs As ADODB.Recordset

Set rs = New ADODB.Recordset

Call connectdb

rs.Open "select * from employee", cnn, adOpenStatic, adLockOptimistic, 1

Do While Not IsEmpty(Range("a" & srow))

With rs

.AddNew

.Fields("Empid") = Range("a" & srow)

.Fields("empname") = Range("b" & srow)

.Fields("salary") = Range("c" & srow)

End With

srow = srow + 1

Loop

MsgBox "records added sucessfully"

Range("a2:c50000").ClearContents

Set rs = Nothing

Call disconnectdb

End Sub

Retrieve the records from access database:


Public cnn As ADODB.Connection

Dim r As Integer, c As Integer

Sub connectdb()

Dim strpath As String

Set cnn = New ADODB.Connection

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

Set cnn = Nothing

End Sub

Sub retriverecords()

Dim srow As Long

srow = 2

Dim rs As ADODB.Recordset

Set rs = New ADODB.Recordset


Call connectdb

rs.Open "select * from employee", cnn, adOpenStatic, adLockOptimistic, 1

Do While Not rs.EOF

Range("a" & srow) = rs("empid")

Range("b" & srow) = rs("empname")

Range("c" & srow) = rs("salary")

srow = srow + 1

rs.MoveNext

Loop

MsgBox "records retrived sucessfully"

Set rs = Nothing

Call disconnectdb

End Sub

Вам также может понравиться