Excel VBA Code Snippet - qa gang - · PDF fileBack to Content Code Snippet A macro is a piece...

51
Excel VBA Code Snippet Author: Amit Shah Version: Version 1.0

Transcript of Excel VBA Code Snippet - qa gang - · PDF fileBack to Content Code Snippet A macro is a piece...

Excel VBA Code Snippet

Author: Amit Shah

Version: Version 1.0

Table of Contents Code Snippet ................................................................................................................................................. 7

Code to Open Existing Workbook ................................................................................................................. 8

Code to Create Excel Object:- ................................................................................................................... 8

Code to Open Excel and Create Object for the same:- ............................................................................. 8

Code to open txt file in the new workbook:- ............................................................................................ 8

Code to Suppressing Excel Warnings:- ...................................................................................................... 9

Code to make excel visible:- ..................................................................................................................... 9

Code to check whether a Sheet in an open workbook exists:- ................................................................. 9

Code to create object to access specific worksheet:- ............................................................................... 9

Code to make worksheet unprotect during runtime:- ........................................................................... 10

Code to make worksheet protected during runtime:- ............................................................................ 10

Code to Make Specified range / column / cell locked during runtime:- ................................................. 10

Code to get Row Count of Specific worksheet:- ..................................................................................... 10

Code to get Column Count of Specific worksheet:- ................................................................................ 11

Code to select Single cell, Contiguous, Non Contiguous range:- ............................................................ 11

Code to get address of the specified cell:- .............................................................................................. 11

Code to get value of the specified cell:-.................................................................................................. 11

Code to get Formula of the Specified cell:- ............................................................................................. 11

Code to use Offset Range Property:- ...................................................................................................... 12

Code to Removes duplicate values:- ....................................................................................................... 12

Code to Creates a data series in the specified range:- ........................................................................... 12

Code to change font of the specified Range or Cell:- ............................................................................. 13

Code to change font Style of the specified Range or Cell:-..................................................................... 13

Code to change font Size of the specified Range or Cell:- ...................................................................... 13

Code to change font color of the specified Range or Cell:- .................................................................... 13

Code to fill Red color of the specified Range or Cell:- ............................................................................ 13

Code to change worksheets / tab color:- ................................................................................................ 14

Code to move worksheets:- .................................................................................................................... 14

Code to change horizontal alignment of the specified Range or Cell:- .................................................. 14

Code to change vertical alignment of the specified Range or Cell:- ....................................................... 14

Code to wrap text of the specified Range or Cell:- ................................................................................. 14

Code to assign column width for the specified column:- ....................................................................... 15

Code to make columns data autofit:- ..................................................................................................... 15

Code to add validation at the specified column during runtime:- .......................................................... 15

Code to delete validation at the specified column during runtime ........................................................ 16

Code to Performs an autofill on the cells in the specified range:- ......................................................... 16

Code to Represents the collection of hyperlinks for a worksheet or range:- ......................................... 16

Code to Clear Contents of the specified Range or Cell:- ......................................................................... 16

Code to Merge selected range:- ............................................................................................................. 16

Code to UnMerge selected Cell:- ............................................................................................................ 17

Code to change the Formatcell:-............................................................................................................. 17

Code to change the Formatcell:-............................................................................................................. 17

Code to AutoFilter with Single Criteria for the column:- ........................................................................ 17

Code to AutoFilter using RegEx with Single Criteria for the column:- .................................................... 17

Code to AutoFilter Using Cell Color with Single Criterial for the Column:- ............................................ 17

Code to AutoFilter with Multiple Criteria for the column:- .................................................................... 18

Code to sort the values in the worksheet in the ascending & descending order:- ................................ 18

Code to do AdvancedFilter on the specified range:- .............................................................................. 18

Code to let you modify any sequence using characters Property:- ........................................................ 19

Code to get address of the range from Filtered Cells:- ........................................................................... 19

Code to insert Column during runtime:- ................................................................................................. 19

Code to Delete Column during runtime:- ............................................................................................... 19

Code to insert Row during runtime:- ...................................................................................................... 19

Code to Delete row during runtime:- ..................................................................................................... 19

Code to Add Conditional formatting to a specified cell or range:- ......................................................... 20

Code to Delete Conditional formatting to a specified cell or range:- ..................................................... 20

Code to Add Comment to a specified cell or range:- .............................................................................. 20

Code to Delete Comment to a specified cell or range:- .......................................................................... 21

Code to copy the specified range during runtime:- ................................................................................ 21

Code to Paste the specified range during runtime:- ............................................................................... 21

Code to PasteSpecial the specified range during runtime:- ................................................................... 21

Code to delete worksheets:- ................................................................................................................... 21

Code to Save the workbook:- .................................................................................................................. 22

Code to close the workbook:- ................................................................................................................. 22

Code to Quit the workbook:- .................................................................................................................. 22

Formula to get count of total working days in the month:- ................................................................... 22

MkDir Statement:- .................................................................................................................................. 22

RmDir Statement:- .................................................................................................................................. 22

FileCopy Statement:- .............................................................................................................................. 23

FileLen Function:- .................................................................................................................................... 23

FileDateTime Function:- .......................................................................................................................... 23

Kill Statement:- ....................................................................................................................................... 23

VLookup Function:- ................................................................................................................................. 24

HLookup Function:- ................................................................................................................................. 24

PIVOT Table Function:- ........................................................................................................................... 25

CurrentRegion Property:- ........................................................................................................................ 27

Code to Create New Workbook and SaveAs on the Local .......................................................................... 28

Code to add workbook during run-time using excel object:- ................................................................. 28

Code to add worksheet during run-time using excel object:- ................................................................ 28

Code to SaveAs Workbook during run-time using excel object:- ........................................................... 28

Code to delete worksheets:- ................................................................................................................... 28

Code to Save ActiveWorkbooks:- ............................................................................................................ 28

Code to Close the workbook:- ................................................................................................................ 29

Code to Quit the workbook:- .................................................................................................................. 29

Excel VBA Properties, Methods & Events ................................................................................................... 30

WORKBOOK:- .......................................................................................................................................... 30

Properties - .......................................................................................................................................... 30

Methods - ............................................................................................................................................ 30

Events - ................................................................................................................................................ 30

WORKSHEETS:- ........................................................................................................................................ 30

Properties - .......................................................................................................................................... 30

Methods - ............................................................................................................................................ 30

Events - ................................................................................................................................................ 30

RANGE:- ................................................................................................................................................... 31

Properties - .......................................................................................................................................... 31

Methods - ............................................................................................................................................ 31

Excel VBA Programming STRING Functions ................................................................................................ 32

ASC:- ........................................................................................................................................................ 32

CHR:- ....................................................................................................................................................... 32

Instr:- ....................................................................................................................................................... 33

InstrB:- ..................................................................................................................................................... 33

InstrRev:- ................................................................................................................................................. 33

Len:- ........................................................................................................................................................ 34

Left:- ........................................................................................................................................................ 34

Right:- ...................................................................................................................................................... 34

Trim, LTrim & RTrim:- .............................................................................................................................. 34

Lcase:- ..................................................................................................................................................... 35

Ucase:- .................................................................................................................................................... 35

Space:- ..................................................................................................................................................... 35

Mid:- ........................................................................................................................................................ 35

Replace:- ................................................................................................................................................. 35

StrReverse: .............................................................................................................................................. 36

StrComp:- ................................................................................................................................................ 36

String:- ..................................................................................................................................................... 36

Split:- ....................................................................................................................................................... 36

LBound:- .................................................................................................................................................. 37

UBound:- ................................................................................................................................................. 37

Date:- ...................................................................................................................................................... 37

DateAdd:- ................................................................................................................................................ 37

DateDiff:- ................................................................................................................................................. 38

DateSerial:-.............................................................................................................................................. 38

Msgbox:- ................................................................................................................................................. 38

InputBox:-................................................................................................................................................ 38

Join:- ........................................................................................................................................................ 39

Filter:- ...................................................................................................................................................... 39

Excel VBA Programming INTEGER Functions .............................................................................................. 40

SQR:- ....................................................................................................................................................... 40

EXP:- ........................................................................................................................................................ 40

LOG:- ....................................................................................................................................................... 40

RND:- ....................................................................................................................................................... 41

ABS:- ........................................................................................................................................................ 41

SGN:- ....................................................................................................................................................... 41

INT & FIX:- ............................................................................................................................................... 42

HEX:- ........................................................................................................................................................ 42

Excel VBA Programming TYPE CHECK Functions ......................................................................................... 43

isArray:- ................................................................................................................................................... 43

isDate:- .................................................................................................................................................... 43

isEmpty:- ................................................................................................................................................. 43

isNull:- ..................................................................................................................................................... 44

isNumeric:- .............................................................................................................................................. 44

Excel VBA Conditional Statements .............................................................................................................. 45

If...Then...Else Statements:- .................................................................................................................... 45

Select Case Statements:- ........................................................................................................................ 46

Excel VBA Loops .......................................................................................................................................... 47

While...Wend Statement:- ...................................................................................................................... 47

Do...Loop Statements:- ........................................................................................................................... 47

For...Next Statement:- ............................................................................................................................ 48

For Each...Next Statement:- .................................................................................................................... 49

With Statement:- .................................................................................................................................... 49

Error Handling ............................................................................................................................................. 50

On Error GoTo:- ....................................................................................................................................... 50

Excel VBA Short-Cuts ................................................................................................................................... 51

Back to Content

Code Snippet A macro is a piece of computer code, that is written from excel, using visual basic application

programming language. Use VBA and macros to automate virtually any routine task, and save yourself

hours, day, maybe even weeks. Visual basic application (VBA) gives experienced Excel users a wide range

of options for creating Excel spreadsheets and customizing how they look and execute functions.

This document reveals code snippet & scripting technique, which helps you to create automated reports

that are amazingly powerful and useful. It also helps you instantly visualize information so you can

understand and act on it. It also shows you how to capture data from anywhere and use it anywhere.

How to write a macro

1. Choose Developer | On Developer Tab Click Insert

2. In the ActiveX control group, click Command button

3. Drag a command button on your worksheet

4. Right Click on command button (make sure design mode is selected).

5. Click View Code

6. Visual basic editor appears

7. Place your cursor between private sub commandbutton1_Click() and End Sub

8. Add the code here

9. Close the Visual basic editor

10. Click the command button on the sheet (make sure design mode is deselected).

How to Record a macro

1. Choose Developer | Record Macro

2. Enter Macro Name. No space allowed

3. Optional: Specify a keyboard shortcut, macro location and description

4. Click OK

5. Perform the actions

6. Choose Developer | Stop Recording

NOTE:

In Code snippet I have used Object for Workbook i.e. oExcel1_Workbook1 & Worksheet i.e.

oExcel1_Worksheet1, instead we can use workbook name like Workbooks (“file1.xls”).Activate &

worksheet name like Worksheets (“sheet1”).Delete.

Below are few examples:

Using Object Using Name

oExcel1_Workbook1.Save Workbooks (“file1.xls”).Save

oExcel1_Worksheet1.Cells(1, 1).Value Worksheets (“sheet1”).Cells(1,1).value

oExcel1_Worksheet1.Unprotect "XX" Worksheets (“sheet1”). Unprotect "XX"

oExcel1_Worksheet1. Delete Worksheets (“sheet1”). Delete

Back to Content

Code to Open Existing Workbook

Code to Create Excel Object:-

SYNTAX =>

Set oExcel1 = CreateObject("Excel.Application")

Code to Open Excel and Create Object for the same:-

EXAMPLE =>

Set oExcel1_Workbook1 = oExcel1.Workbooks.Open ("C:\NewFolder1\ NewFolder2\

NewFolder3\file1.xls")

Code to open txt file in the new workbook:-

Loads and parses a text file (.txt) as a new workbook with a single sheet that contains the parsed

text-file data

SYNTAX =>

expression.OpenText(Filename, Origin, StartRow, DataType, TextQualifier, ConsecutiveDelimiter,

Tab, Semicolon, Comma, Space, Other, OtherChar, FieldInfo, TextVisualLayout,

DecimalSeparator, ThousandsSeparator, TrailingMinusNumbers, Local)

EXAMPLE =>

oExcel1.Workbooks.OpenText Filename:="C:\ NewFolder1\ NewFolder2\ NewFolder3\

NewFolder4\file1.txt", DataType:=xlDelimited, Semicolon:=True

oExcel1.Workbooks.OpenText Filename:=" C:\ NewFolder1\ NewFolder2\ NewFolder3\

NewFolder4\file1.txt ", DataType:=xlDelimited, Comma:=True

oExcel1.Workbooks.OpenText Filename:=" C:\ NewFolder1\ NewFolder2\ NewFolder3\

NewFolder4\file1.txt ", DataType:=xlDelimited, Space:=True

Set oExcel1_Worksheet1 = oExcel1.ActiveWorkbook.Worksheets(1)

Code to Suppressing Excel Warnings:-

The default value is True. Set this property to False to suppress prompts and alert messages

while a macro is running; when a message requires a response, Microsoft Excel chooses the default

response

SYNTAX =>

expression. DisplayAlerts = True / False

EXAMPLE =>

Application.DisplayAlerts = False

Code to make excel visible:-

SYNTAX =>

oExcel1.Application.Visible = False

Code to check whether a Sheet in an open workbook exists:-

EXAMPLE =>

On Error Resume Next

Set wsheet = ActiveWorkbook.Sheets("Sheet4")

If wsheet Is Nothing Then

MsgBox "Fail"

Else

MsgBox "Pass"

End If

Code to create object to access specific worksheet:-

EXAMPLE =>

Set oExcel1_Worksheet1 = oExcel1.Workbooks ("C:\ NewFolder1\ NewFolder2\

NewFolder3\file1.xls").Worksheets ("Sheet1")

Code to make worksheet unprotect during runtime:-

Removes protection from a sheet or workbook. This method has no effect if the sheet or

workbook isn't protected

SYNTAX =>

expression.Unprotect (Password)

EXAMPLE =>

oExcel1_Worksheet1.Unprotect "XX"

Code to make worksheet protected during runtime:-

Protects a workbook so that it cannot be modified.

SYNTAX =>

expression. Protect (Password)

EXAMPLE =>

oExcel1_Worksheet1.Protect "XX"

Code to Make Specified range / column / cell locked during runtime:-

EXAMPLE =>

oExcel1_Worksheet1.Range("C:D").Locked = True / False

Code to get Row Count of Specific worksheet:-

EXAMPLE =>

WBRowCount = oExcel1_Worksheet1.Cells(oExcel1_Worksheet1.Rows.Count,

"A").End(xlUp).Row

Code to get Column Count of Specific worksheet:-

EXAMPLE =>

ColCount1 = oExcel1_Worksheet1.Cells (1,

oExcel1_Worksheet1.Columns.Count).End(xlToLeft).Column

Code to select Single cell, Contiguous, Non Contiguous range:-

EXAMPLE =>

oExcel1_Worksheet1.Range("A1").Select

oExcel1_Worksheet1.Range("A1:G5:").Select

oExcel1_Worksheet1.Range("A1:G5,J9:H10").Select

Code to get address of the specified cell:-

EXAMPLE =>

CellAddress = oExcel1_Worksheet1.Cells(1, 1).Address

Code to get value of the specified cell:-

SYNTAX =>

expression. Cells (Row,Column)

EXAMPLE =>

CellValue = oExcel1_Worksheet1.Cells(1, 1).Value

Code to get Formula of the Specified cell:-

SYNTAX =>

expression. Cells (Row,Column)

EXAMPLE =>

CellFormula = oExcel1_Worksheet1.Cells(1, 1).Formula

Code to use Offset Range Property:-

SYNTAX =>

expression. Offset (Row,Column)

EXAMPLE =>

oExcel1_Worksheet1.Range("A1").Offset(1,1).Select -> Select Cell B2

oExcel1_Worksheet1.Range("A1").Offset(1).Select -> Select Cell A2

oExcel1_Worksheet1.Range("A1").Offset(,1).Select -> Select Cell B1

oExcel1_Worksheet1.Range("B2").Offset(-1,-1).Select -> Select Cell A1

Code to Removes duplicate values:-

SYNTAX =>

expression. RemoveDuplicates(Columns, Header)

EXAMPLE =>

oExcel1_Worksheet1.Range("A1:B100").RemoveDuplicates Array(2), xlYes

oExcel1_Worksheet1.Range("A1:B100").RemoveDuplicates Array(1, 2), xlNo

Code to Creates a data series in the specified range:-

SYNTAX =>

expression. DataSeries(RowCol, Type,Date,Step,Stop,Trend)

EXAMPLE =>

oExcel1_Worksheet1.Range("D1").Formula = "31-JAN-1996"

oExcel1_Worksheet1.Range("D1:D12").DataSeries Type:=xlChronological, Date:=xlDay -> Day

oExcel1_Worksheet1.Range("D1:D12").DataSeries Type:=xlChronological, Date:=xlMonth ->

Month

oExcel1_Worksheet1.Range("D1:D18").DataSeries Type:=xlChronological, Date:=xlWeekday ->

Weekday

oExcel1_Worksheet1.Range("D1:D18").DataSeries Type:=xlChronological, Date:=xlYear -> Year

oExcel1_Worksheet1.Range("D1").Value = 1

oExcel1_Worksheet1.Range("D1:D18").DataSeries Type:=xlDataSeriesLinear -> Extend values in

sequence

Code to change font of the specified Range or Cell:-

EXAMPLE =>

oExcel1_Worksheet1.Range("A1:K1").Font.Name = "Arial"

oExcel1_Worksheet1.Cells(1, 1).Font.Name = "Arial"

Code to change font Style of the specified Range or Cell:-

EXAMPLE =>

oExcel1_Worksheet1.Range("A1:K1").Font.FontStyle = "Bold Italic"

oExcel1_Worksheet1.Cells(1, 1).Font.FontStyle = "Bold Italic"

Code to change font Size of the specified Range or Cell:-

EXAMPLE =>

oExcel1_Worksheet1.Range("A1:K1").Font.Size = 10

oExcel1_Worksheet1.Cells(1, 1).Font.Size = 10

Code to change font color of the specified Range or Cell:-

EXAMPLE =>

oExcel1_Worksheet1.Range("A1:K1").Font.ColorIndex = 2

oExcel1_Worksheet1.Cells(1, 1).Font.ColorIndex = 2

Code to fill Red color of the specified Range or Cell:-

EXAMPLE =>

oExcel1_Worksheet1.Range("B2:B6").Interior.ColorIndex = 10

oExcel1_Worksheet1.Cells(1, 1).Interior.ColorIndex = 10

Code to change worksheets / tab color:-

EXAMPLE =>

oExcel1.Worksheets("Sheet1").Tab.ColorIndex = 6 -> yellow

oExcel1.Worksheets("Sheet3").Tab.ColorIndex = 4 -> Green

Code to move worksheets:-

EXAMPLE =>

Worksheets("Sheet1").Move Before:=Worksheets("Sheet2")

Worksheets("Sheet1").Move After:=Worksheets("Sheet2")

Code to change horizontal alignment of the specified Range or Cell:-

EXAMPLE =>

oExcel1_Worksheet1.Range("A1:K1").HorizontalAlignment = xlLeft / xlGeneral

oExcel1_Worksheet1.Cells(1, 1).HorizontalAlignment = xlLeft / xlGeneral

Code to change vertical alignment of the specified Range or Cell:-

EXAMPLE =>

oExcel1_Worksheet1.Range("A1:K1").VerticalAlignment = xlVAlignCenter / xlTop

oExcel1_Worksheet1.Cells(1, 1).VerticalAlignment = xlVAlignCenter / xlTop

Code to wrap text of the specified Range or Cell:-

EXAMPLE =>

oExcel1_Worksheet1.Range("A1:C1").WrapText = True

oExcel1_Worksheet1.Cells(1, 1).WrapText = True

Code to assign column width for the specified column:-

EXAMPLE =>

oExcel1_Worksheet1.Columns("C").ColumnWidth = 120

Code to make columns data autofit:-

EXAMPLE =>

oExcel1_Worksheet1.Columns("A:K").AutoFit

Code to add validation at the specified column during runtime:-

Note -> Please Change "Formula1" to add different values in the validation:

EXAMPLE =>

With oExcel1_Worksheet1.Range("A1:A100").Validation

.Delete

.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween,

Formula1:="NA, Amit, Mamta"

.IgnoreBlank = True

.InCellDropdown = True

.InputTitle = ""

.ErrorTitle = ""

.InputMessage = ""

.ErrorMessage = ""

.ShowInput = True

.ShowError = True

End With

Code to delete validation at the specified column during runtime SYNTAX =>

expression. Validation.Delete

EXAMPLE =>

Worksheet1Range("A10:A100”).Validation.Delete

Code to Performs an autofill on the cells in the specified range:-

SYNTAX =>

expression.AutoFill(Destination, Type)

EXAMPLE =>

oExcel1_Worksheet1.Range("A2").AutoFill oExcel1_Worksheet1.Range("A2:A100"), 0

Code to Represents the collection of hyperlinks for a worksheet or range:-

EXAMPLE =>

oExcel1_Worksheet1.Range("K2").Select

Selection.Hyperlinks.Add Anchor:=Selection, Address:="Amit Shah", TextToDisplay:="Amit Shah"

Code to Clear Contents of the specified Range or Cell:-

EXAMPLE =>

oExcel1_Worksheet1.Range("A10:A100").ClearContents

oExcel1_Worksheet1.Cells(1, 1).ClearContents

Code to Merge selected range:-

EXAMPLE =>

oExcel1_Worksheet1.Range("C4:C10").Select

Selection.Merge

Code to UnMerge selected Cell:-

Note -> If a = True than only Unmerge the cells

EXAMPLE =>

a = oExcel1_Worksheet1.Cells(1, 3).MergeCells

oExcel1_Worksheet1.Cells(1, 3).UnMerge

Code to change the Formatcell:-

EXAMPLE =>

oExcel1_Worksheet1.Range("A2").NumberFormat = "General" -> Cell

oExcel1_Worksheet1.Range("A:A").NumberFormat = "General" -> Column

Code to change the Formatcell:-

EXAMPLE =>

oExcel1_Worksheet1.Range("A2").NumberFormat = "@" -> Cell

oExcel1_Worksheet1.Range("A:A").NumberFormat = "@" -> Column

Code to AutoFilter with Single Criteria for the column:-

EXAMPLE =>

oExcel1_Worksheet1.Range("A1").AutoFilter Field:=1, Criteria1:="Amit", VisibleDropDown:=True

Code to AutoFilter using RegEx with Single Criteria for the column:-

EXAMPLE =>

oExcel1_Worksheet1.Range("A1").AutoFilter Field:=1, Criteria1:="abc*", VisibleDropDown:=True

Code to AutoFilter Using Cell Color with Single Criterial for the Column:-

EXAMPLE =>

oExcel1_Worksheet1.Range("A1").AutoFilter Field:=1, Criteria1:=RGB(255, 0, 0),

Operator:=xlFilterCellColor, VisibleDropDown:=True ‘Filter with cell color as Red

oExcel1_Worksheet1.Range("A1").AutoFilter Field:=1, Criteria1:=RGB(0, 255, 0), Operator

:=xlFilterCellColor, VisibleDropDown:=True ‘Filter with cell color as Green

oExcel1_Worksheet1.Range("A1").AutoFilter Field:=1, Criteria1:=RGB(0, 0, 255), Operator

:=xlFilterCellColor, VisibleDropDown:=True ‘Filter with cell color as Blue

Code to AutoFilter with Multiple Criteria for the column:-

EXAMPLE =>

oExcel1_Worksheet1.Range("A1").AutoFilter Field:=1, Operator:=xlFilterValues,

Criteria2:=Array(1, currentmonth, 1, Previousmonth), VisibleDropDown:=False

Code to sort the values in the worksheet in the ascending & descending order:-

EXAMPLE =>

Set excelrange = oExcel1_Worksheet1.UsedRange

Set objrange15 = ObjExcel.Range("A1")

excelrange.sort objrange15,xlAscending,,,,,,1

excelrange.sort objrange15,xlDescending,,,,,,1

Code to do AdvancedFilter on the specified range:-

Note -> AdvancedFilter(Action, CriteriaRange, CopyToRange, Unique)

EXAMPLE =>

oExcel1_Worksheet1.Range("A1:B12").AdvancedFilter xlFilterInPlace, Range("B1:B4"), , False

Output-> Filters data from a list based on a criteria range

oExcel1_Worksheet1.Range("A1:B12").AdvancedFilter xlFilterCopy, Range("B1:B4"),

Range("E1:F12"), False

Output-> Copies data from a list based on a criteria range

Code to let you modify any sequence using characters Property:-

EXAMPLE =>

oExcel1_Worksheet1.Range("A2").Characters(7, 4).Font.Bold = True

oExcel1_Worksheet1.Range("A2").Characters(7, 4).Font.Italic = True

Code to get address of the range from Filtered Cells:-

EXAMPLE =>

Set Rng = oExcel1_Worksheet1.AutoFilter.Range

FilteredCells = Rng.SpecialCells(xlCellTypeVisible).Address

Code to insert Column during runtime:-

EXAMPLE =>

Set objrange = oExcel1.Range("A1").EntireColumn

objrange.Insert (xlShiftToRight)

Code to Delete Column during runtime:-

EXAMPLE =>

Set objrange = oExcel1.Range("A1").EntireColumn.delete

Code to insert Row during runtime:-

EXAMPLE =>

Set objrange = oExcel1.Range("3:3").EntireRow

objrange.Insert (xlShiftToDown)

Code to Delete row during runtime:-

EXAMPLE =>

Set objrange = oExcel1.Range("3:3").EntireRow.delete

Code to Add Conditional formatting to a specified cell or range:-

EXAMPLE =>

Range("G3:G18").FormatConditions.Add Type:=xlTextString, String:="Done",

TextOperator:=xlContains

Range("G3:G18").FormatConditions(Range("G3:G18").FormatConditions.Count).SetFirstPriority

With Range("G3:G18").FormatConditions(1).Font

.ColorIndex = 6

End With

Range("G3:G18").FormatConditions(1).Interior.ColorIndex = 3

Range("H1:H18").FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, Formula1:="=10"

Range("H1:H18").FormatConditions(Range("H1:H18").FormatConditions.Count).SetFirstPriority

With Range("H1:H18").FormatConditions(1).Font

.ColorIndex = 6

End With

Range("H1:H18").FormatConditions(1).Interior.ColorIndex = 3

Code to Delete Conditional formatting to a specified cell or range:-

EXAMPLE =>

Range("G3:G18").FormatConditions.Delete

Code to Add Comment to a specified cell or range:-

EXAMPLE =>

Range("A15").AddComment

Range("A15").Comment.Visible = True

Range("A15").Comment.Text Text:=""Enter Hello Here”

Code to Delete Comment to a specified cell or range:-

EXAMPLE =>

If Range("A15").Comment Is Nothing Then

Else

Range("A15").Comment.Delete

End If

Code to copy the specified range during runtime:-

EXAMPLE =>

oExcel1_Worksheet1.Range("A1:D10").Copy

Code to Paste the specified range during runtime:-

EXAMPLE =>

oExcel1_Worksheet1.Range("A1:A18").Copy

oExcel1_Worksheet1.Paste Worksheets("Sheet1").Range("K1:K18")

Code to PasteSpecial the specified range during runtime:-

EXAMPLE =>

oExcel1_Worksheet1.Range("A2:A18").Copy

oExcel1_Worksheet1.Range("K2:K18").PasteSpecial -4163 -> xlPasteValues

oExcel1_Worksheet1.Range("K2:K18").PasteSpecial -4123 -> xlPasteFormulas

oExcel1_Worksheet1.Range("K2:K18").PasteSpecial 12 -> xlPasteValuesAndNumberFormats

Code to delete worksheets:-

EXAMPLE =>

oExcel1_Workbook1.Workbooks("C:\ NewFolder1\ NewFolder2\

NewFolder3\file1.xls").Worksheets("Sheet3").Delete

Code to Save the workbook:-

EXAMPLE =>

oExcel1_Workbook1.Workbooks("C:\ NewFolder1\ NewFolder2\ NewFolder3\file1.xls ").Save

Code to close the workbook:-

EXAMPLE =>

oExcel1_Workbook1.Workbooks("C:\ NewFolder1\ NewFolder2\ NewFolder3\file1.xls ").Close

Code to Quit the workbook:-

EXAMPLE =>

oExcel1_Workbook1.Quit

Formula to get count of total working days in the month:-

Note -> A100 is the cell containing date

EXAMPLE =>

=NETWORKDAYS(A100-DAY(A100)+1,DATE(YEAR(A100),MONTH(A100)+1,0))

MkDir Statement:- Creates a new directory or folder.

SYNTAX => MkDir path

EXAMPLE => MkDir "C:\ NewFolder1\ NewFolder2\ NewFolder3\MYDIR"

RmDir Statement:-

Removes an existing directory or folder.

SYNTAX => RmDir path

EXAMPLE => RmDir "C:\ NewFolder1\ NewFolder2\ NewFolder3\MYDIR"

FileCopy Statement:-

Copies a file.

SYNTAX => FileCopy source, destination

EXAMPLE => FileCopy "C:\ NewFolder1\ NewFolder2\ NewFolder3\file1.doc", "C:\ NewFolder1\

NewFolder2\ NewFolder3\file1.doc"

FileLen Function:-

Returns a Long specifying the length of a file in bytes.

SYNTAX => FileLen(pathname)

EXAMPLE => a = FileLen("C:\ NewFolder1\ NewFolder2\ NewFolder3\file1.doc")

FileDateTime Function:-

Returns a Variant (Date) that indicates the date and time when a file was created or last

modified.

SYNTAX => FileDateTime(pathname)

EXAMPLE => a = FileDateTime("C:\ NewFolder1\ NewFolder2\ NewFolder3\file1.doc")

Kill Statement:-

Deletes files from a disk.

SYNTAX => Kill pathname

EXAMPLE => Kill "C:\ NewFolder1\ NewFolder2\ NewFolder3\file1.docx" - Delete specific file

EXAMPLE => Kill "C:\ NewFolder1\ NewFolder2\ NewFolder3\*.xls" - Delete all excel file from

the specified path

VLookup Function:-

Vlookup is generally used to look up a particular value in the huge datasheet. Searches for a

value in the first column of a table array and returns a value in the same row from another

column in the table array.

Use of Vlookup –

1) To lookup a single or set of values from the data sheet.

2) To add a column to a data sheet from some other table.

SYNTAX =>

Application.Vlookup(Lookup_Value, Table_array, Column_Index, Range_Lookup)

Application.WorksheetFunction.Vlookup(Lookup_Value, Table_array, Column_Index,

Range_Lookup)

VLOOKUP (lookup_value, table_array, Column_Index, range_lookup)

EXAMPLE =>

1) Application.Vlookup(“Amit”, “B3:D13”, 3, False)

2) =Vlookup(“Amit”, $B$3:$D$13, {1,2,3,4} , False)

Select the exact number of cells from the above e.g. 5 cells than write the above

formula and then press ‘ctrl+shift+enter’

3) Application.WorksheetFunction.Vlookup (“A*”, “B3:D13”, 3, False)

4) =IF(ISNA(VLOOKUP(“Amit”,$G$16:$G$28,1,0)),"Not Exists","Exists")

Check if the value exists in the master list.

Few Important Points –

1) Vlookup Function performs a case insensitive lookup

2) Vlookup returns ‘#N/A’ if it is not able to find lookup value inside the table array.

3) Vlookup returns ‘#value!’ if the value of ‘column_index’ is less than the table array.

4) Vlookup returns ‘#Ref!’ if the value of ‘column_index’ is greater than the table array.

HLookup Function:-

Searches for a value in the top row of a table or an array of values, and then returns a value in

the same column from a row you specify in the table or array. Use HLOOKUP when your

comparison values are located in a row across the top of a table of data, and you want to look

down a specified number of rows. Use VLOOKUP when your comparison values are located in a

column to the left of the data you want to find.

SYNTAX =>

Application. HLOOKUP (Lookup_Value, Table_array, row_index_num, Range_Lookup)

Application.WorksheetFunction. HLOOKUP (Lookup_Value, Table_array,

row_index_num, Range_Lookup)

HLOOKUP (lookup_value, table_array, row_index_num, [range_lookup])

EXAMPLE =>

=HLOOKUP ("Axles", A1:C4, 2, TRUE) OUTPUT -> Looks up Axles in row 1, and returns the

value from row 2 that's in the same column.

Application. HLOOKUP (“Amit”, “B3:D13”, 3, False)

Few Important Points –

1) Hlookup Function performs a case insensitive lookup

2) If lookup_value is smaller than the smallest value in the first row of table_array, HLOOKUP

returns the ‘#N/A’ error value.

3) If range_lookup is FALSE and lookup_value is text, you can use the wildcard characters,

question mark (?) and asterisk (*), in lookup_value. A question mark matches any single

character; an asterisk matches any sequence of characters. If you want to find an actual

question mark or asterisk, type a tilde (~) before the character.

PIVOT Table Function:-

Represents a PivotTable report on a worksheet. The PivotTable object is a member of the PivotTables collection. The PivotTables collection contains all the PivotTable objects on a single worksheet. Because PivotTable report programming can be complex, it’s generally easiest to record PivotTable report actions and then revise the recorded code

EXAMPLE =>

Dim ws As Worksheet

Dim pc As PivotCache

Dim pt As PivotTable

Set ws = Worksheets.Add

Set pc = ActiveWorkbook.PivotCaches.Create(xlDatabase, "Sheet1!R1C1:R10C3")

Set pt = pc.CreatePivotTable(ws.Range("A3"))

With pt

With .PivotFields("Department")

.Orientation = xlRowField

.Position = 1

End With

With .PivotFields("Region")

.Orientation = xlColumnField

.Position = 1

End With

.AddDataField .PivotFields("Profit"), "Sum of Profit", xlSum

End With

Below is the data needed to be available on sheet1 for creating pivot table.

PIVOTCHART:-

Represents a chart in a workbook. The chart can be either an embedded chart (contained in a ChartObject object) or a separate chart sheet. The following properties and methods for returning a Chart object are described in the example section:

EXAMPLE =>

Dim pt As PivotTable

Dim ptr As Range

Dim cht As Chart

If ActiveSheet.PivotTables.Count = 0 Then

Exit Sub

End If

Set pt = ActiveSheet.PivotTables(1)

Set ptr = pt.TableRange1

Set cht = Charts.Add

With cht

.SetSourceData ptr

Department Region Profit

109 5 11900

107 3 400

109 2 1200

108 6 78

.ChartType = xlLine

.HasTitle = True

.ChartTitle.Text = "Code Snippet for Pivot Chart"

End With

CurrentRegion Property:-

Returns a Range object that represents the current region. The current region is a range bounded by any

combination of blank rows and blank columns. Read-only.

SYNTAX =>

Expression.CurrentRegion

EXAMPLE =>

Range("A1").CurrentRegion.Select ‘Select the Range

Range("A1").CurrentRegion.AutoFilter ‘Add autofilter to the Range

a = Range("A1").CurrentRegion.Address ‘Return the address of the selected range.

MsgBox a

Back to Content

Code to Create New Workbook and SaveAs on the Local

Code to add workbook during run-time using excel object:-

SYNTAX =>

Set oExcel2 = CreateObject("Excel.Application")

oExcel2.Workbooks.Add

Code to add worksheet during run-time using excel object:-

EXAMPLE =>

oExcel2.Worksheets.Add

Set Sheet_One = oExcel2.ActiveSheet

Sheet_One.Name = "Amit"

Code to SaveAs Workbook during run-time using excel object:-

EXAMPLE =>

oExcel2.ActiveWorkbook.SaveAs ("C:\ NewFolder1\ NewFolder2\ NewFolder3\file1.xls")

Code to delete worksheets:-

EXAMPLE =>

oExcel2.Worksheets("Sheet1").Delete

Code to Save ActiveWorkbooks:-

EXAMPLE =>

oExcel2.ActiveWorkbook.Save

Code to Close the workbook:-

EXAMPLE =>

oExcel2.ActiveWorkbook.Close

Code to Quit the workbook:-

EXAMPLE =>

oExcel2.Application.Quit

Back to Content

Excel VBA Properties, Methods & Events

WORKBOOK:-

Properties -

ActiveChart, ActiveSheet, AutoUpdateFrequency, Charts, FileFormat, FullName, HasPassword, Name,

Names, Path, ReadOnly, Saved, Sheets, Worksheets

Methods -

Activate, AddToFavorites, ApplyTheme, BreakLink, Close, OpenLinks, PrintOut, PrintPreview, Protect,

Save, SaveAs, Unprotect

Events -

Activate, AfterSave, BeforeClose, BeforePrint, BeforeSave, NewChart, NewSheet, Open, SheetCalculate,

SheetChange, WindowActivate, WindowDeactivate, WindowResize

WORKSHEETS:-

Properties -

AutoFilter, Cells, CircularReference, Columns, Comments, Count, DisplayPageBreaks, EnableAutoFilter,

Hyperlinks, Name, Names, PageSetup, Parent, Range, Rows, Shapes, Sort, StandardHeight,

StandardWidth, Visible

Methods -

Activate, Add, Calculate, Copy, Delete, Move, Paste, PasteSpecial, PivotTableWizard, PrintOut,

PrintPreview, Protect, ResetAllPageBreaks, SaveAs, Save, Unprotect

Events -

Activate, BeforeDoubleClick, BeforeRightClick, Calculate, Change, PivotTableUpdate

RANGE:-

Properties -

AddIndent, Address, AllowEdit, Borders, Cells, Characters, Column, ColumnWidth, Comment, Count,

CurrentRegion, Dependents, End, EntireColumn, EntireRow, Font, Formula,

FormulaR1C1, HasFormula, Height, Hidden, HorizontalAlignment, Hyperlinks, IndentLevel, Interior, Item,

Locked, MergeCells, Name, NumberFormat, Offset, Orientation,

OutlineLevel, PageBreak, Parent, PivotCell, PivotField, PivotItem, PivotTable, Precendents,

PrefixCharacter, Range, Resize, Row, RowHeight, Rows, Text, UseStandardHeight,

UseStandardWidth, Validation, Value, VerticalAlignment, Width, Worksheets, WrapText

Methods -

Activate, AdvancedFilter, AddComment, ApplyNames, AutoFill, AutoFilter, AutoFit, BorderAround,

Calculate, CheckSpelling, Clear, ClearComments, ClearContents,

ClearFormats, ClearHyperlinks, Copy, CreateNames, Cut, DataSeries, Delete, FillDown, FillLeft, FillRight,

FillUp, Find, FindNext, FindPrevious, Insert, InsertIndent,

Justify, Merge, PasteSpecial, PrintOut, PrintPreview, RemoveDuplicates, RemoveSubtotal, Replace,

Select, Sort, Subtotal, TextToColumns, UnMerge

Back to Content

Excel VBA Programming STRING Functions

ASC:- Converts first character of string to its ASCII Value.

EXAMPLE =>

Asc("|") - 124

Asc("{") - 123

Asc("}") - 125

Asc("[") - 91

Asc("]") - 93

Asc(";") - 59

Asc(":") - 58

Asc("-") - 45

Asc("_") - 95

Asc("^") - 94

Asc("~") - 126

CHR:- Converts an ANSI value to a string.

EXAMPLE =>

Chr(32) - Space

Chr(33) - Exclamation !

Chr(34) - Double Quotes "

Chr(36) - Dollar $

Chr(37) - Percent %

Chr(38) - Amspand &

Chr(39) - Single Quotes '

Chr(40) - Opening Round Bracket (

Chr(41) - Closing Round Bracket )

Chr(42) - Multiplication *

Chr(43) - Addition +

Chr(44) - Comma ,

Chr(45) - Hypen -

Chr(46) - Dot .

Chr(47) - Slash /

Instr:- Returns the position of the string with another string.

EXAMPLE =>

a = "My Name is Amit"

b = InStr(1, a, "Name") -> OUTPUT = 4

b = InStr(1, a, "Amit") -> OUTPUT = 12

InstrB:- Returns the byte position of the string with another string.

EXAMPLE =>

a = "My Name is Amit"

b = InStrB(1, a, "Name") -> OUTPUT = 7

b = InStr(1, a, "Amit") -> OUTPUT = 23

InstrRev:- Returns the position of the string with another string beginning at the back end of the string.

EXAMPLE =>

a = "amita xupwxyz"

b = InStrRev(a, "a") -> OUTPUT = 5

a = "mamta xupwxyz"

b = InStrRev(a, "m") -> OUTPUT = 3

Len:- Returns a Long containing the number of characters in a string or the number of bytes required to store

a variable.

EXAMPLE =>

a = "Amit Shah working on Automation"

b = Len(a) -> OUTPUT = 31

Left:- Returns a Variant (String) containing a specified number of characters from the left side of a string.

EXAMPLE =>

a = "Amit Shah working on Automation"

b = Left(a, 4) -> OUTPUT = Amit

b = Left(a, 11) -> OUTPUT = Amit Shah w

Right:- Returns a Variant (String) containing a specified number of characters from the right side of a string.

EXAMPLE =>

a = "Amit Shah working on Automation"

b = Right(a, 4) -> OUTPUT = tion

b = Right(a, 11) -> OUTPUT = Automation

Trim, LTrim & RTrim:- Returns a Variant (String) containing a copy of a specified string without leading spaces (LTrim), trailing

spaces (RTrim), or both leading and trailing spaces (Trim).

EXAMPLE =>

a = " Amit Shah working on Automation "

b = Trim(a) -> OUTPUT = "Amit Shah working on Automation"

b = LTrim(a) -> OUTPUT = "Amit Shah working on Automation "

b = RTrim(a) -> OUTPUT = " Amit Shah working on Automation"

Lcase:- Returns a String that has been converted to lowercase.

EXAMPLE =>

a = "Amit Shah working on Automation"

b = LCase(a) -> OUTPUT = "amit shah working on automation"

Ucase:- Returns a Variant (String) containing the specified string, converted to uppercase.

EXAMPLE =>

a = "Amit Shah working on Automation"

b = UCase(a) -> OUTPUT = "AMIT SHAH WORKING ON AUTOMATION"

Space:- Returns a Variant (String) consisting of the specified number of spaces.

EXAMPLE =>

b = "Amit" & Space(5) & "Shah" -> OUTPUT = "Amit Shah"

Mid:- Returns a Variant (String) containing a specified number of characters from a string.

EXAMPLE =>

a = "Amit Shah working on Automation"

b = Mid(a, 4, 5) -> OUTPUT = "t Sha"

b = Mid(a, 1, 9) -> OUTPUT = "Amit Shah"

Replace:- Returns a string in which a specified substring has been replaced with another substring a specified

number of times.

EXAMPLE =>

a = "Amit Shah working on Automation"

b = Replace(a, " ", "*") -> OUTPUT = "Amit*Shah*working*on*Automation"

b = Replace(a, " ", "_") -> OUTPUT = "Amit_Shah_working_on_Automation"

StrReverse: Returns a string in which the character order of a specified string is reversed.

EXAMPLE =>

a = "Amit Shah working on Automation"

b = StrReverse(a) -> OUTPUT = "noitamotuA no gnikrow hahS timA"

StrComp:- Returns a Variant (Integer) indicating the result of a string comparison.

EXAMPLE =>

MyStr1 = "AMIT"

MyStr2 = "amit"

MyComp = StrComp(MyStr1, MyStr2, 1) -> OUTPUT = 0

String:- Returns a Variant (String) containing a repeating character string of the length specified.

EXAMPLE =>

MyString = String(5, "*") -> OUTPUT = *****

MyString = String(10, "Amit") -> OUTPUT = aaaaaaaaaa

Split:- Returns a zero-based, one-dimensional array containing a specified number of substrings.

EXAMPLE =>

a = "Amit*Shah*working*on*Automation"

b = Split(a, "*") -> OUTPUT

b(0) = Amit

b(1) = Shah

b(2) = working

b(3) = on

b(4) = Automation

LBound:- Returns a Long containing the smallest available subscript for the indicated dimension of an array.

EXAMPLE =>

a = "Amit*Shah*working*on*Automation"

b = Split(a, "*")

c = LBound(b) -> OUTPUT = 0

UBound:- Returns a Long containing the largest available subscript for the indicated dimension of an array.

EXAMPLE =>

a = "Amit*Shah*working*on*Automation"

b = Split(a, "*")

d = UBound(b) -> OUTPUT = 4

Date:- Returns a Variant (Date) containing the current system date.

EXAMPLE =>

a = Date -> OUTPUT = System Date

DateAdd:- Returns a Variant (Date) containing a date to which a specified time interval has been added.

EXAMPLE =>

a = DateAdd("d", 1, "31-Jan-96") -> OUTPUT = 2/1/1996

c = DateAdd("w", 1, "31-Jan-96") -> OUTPUT = 2/1/1996

d = DateAdd("ww", 1, "31-Jan-96") -> OUTPUT = 2/7/1996

a = DateAdd("m", 1, "31-Jan-96") -> OUTPUT = 2/29/1996

a = DateAdd("yyyy", 1, "31-Jan-96") -> OUTPUT = 1/31/1997

DateDiff:- Returns a Variant (Long) specifying the number of time intervals between two specified dates.

EXAMPLE =>

a = DateDiff("d", "30-04-2015", Date) -> OUTPUT = 34

b = DateDiff("m", "31-05-2015", Date) -> OUTPUT = 1

c = DateDiff("w", "30-04-2015", Date) -> OUTPUT = 4

d = DateDiff("ww", "30-04-2015", Date) -> OUTPUT = 5

e = DateDiff("yyyy", "31-01-2014", Date) -> OUTPUT = 1

DateSerial:- Returns a Variant (Date) for a specified year, month, and day.

EXAMPLE =>

a = DateSerial(1969, 2, 12) -> OUTPUT = 2/12/1969

Msgbox:- Displays a message in a dialog box, waits for the user to click a button, and returns an Integer indicating

which button the user clicked.

SYNTAX =>

MsgBox(prompt[, buttons] [, title] [, helpfile, context])

EXAMPLE =>

MsgBox "WELCOME TO VBA MACRO HELP DOCUMENT", 1, "Msgbox Demonstration"

InputBox:- Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns a String

containing the contents of the text box.

SYNTAX =>

InputBox(prompt[, title] [, default] [, xpos] [, ypos] [, helpfile, context])

EXAMPLE =>

MyValue = InputBox("Enter a value between 1 and 3", "InputBox Demo", "1")

Join:- Returns a string created by joining a number of substrings contained in an array.

SYNTAX =>

Join(sourcearray[, delimiter])

EXAMPLE =>

b = Array("Amit", "Shah", "working", "on", "Automation")

a = Join(b, "-") -> OUTPUT = "Amit-Shah-working-on-Automation"

a = Join(b, "&") -> OUTPUT = "Amit&Shah&working&on&Automation"

Filter:- Returns a zero-based array containing subset of a string array based on a specified filter criteria.

SYNTAX =>

Filter(sourcesrray, match[, include[, compare]])

EXAMPLE =>

b = Array("Amit", "Shah", "working", "on", "Automation")

c = Filter(b, "Shah") -> OUTPUT - c(0) = "Shah"

Back to Content

Excel VBA Programming INTEGER Functions

SQR:- Returns a Double specifying the square root of a number

SYNTAX =>

Sqr(number)

EXAMPLE =>

a = Sqr(9) ' Returns 3

b = Sqr(28) ' Returns 5.29

c = Sqr(81) ' Returns 9

EXP:- Returns a Double specifying e (the base of natural logarithms) raised to a power.

SYNTAX =>

Exp(number)

EXAMPLE =>

a = Exp(9) ' Returns 8103.083

b = Exp(1.3) ' Returns 3.6692

c = Exp(1.5) ' Returns 4.4816

LOG:- Returns a Double specifying the natural logarithm of a number.

SYNTAX =>

Log(number)

EXAMPLE =>

a = Log(9) ' Returns 2.1972

b = Log(1.3) ' Returns 0.26236

c = Log(1.5) ' Returns 0.40546

RND:- Returns a Single containing a random number.

SYNTAX =>

Rnd(number)

EXAMPLE =>

a = Rnd(9) ' Returns 0.9619

b = Int((10 - 6 + 1) * Rnd + 6) ' Returns 6

c = Int((110 - 100 + 1) * Rnd + 100) ' Returns 101

Here, upperbound is the highest number in the range, and lowerbound is the lowest number in the

range.

ABS:-

Returns a value of the same type that is passed to it specifying the absolute value of a number.

SYNTAX =>

Abs(number)

EXAMPLE =>

a = abs(9) ' Returns 9

b = abs(100) ' Returns 100

c = abs(-101) ' Returns 101

SGN:-

Returns a Variant (Integer) indicating the sign of a number.

SYNTAX =>

Sgn(number)

EXAMPLE =>

a = Sgn(12) ' Returns 1

b = Sgn(-2) ' Returns -1

c = Sgn(0) ' Returns 0

INT & FIX:-

Returns the integer portion of a number.

SYNTAX =>

Int(number)

Fix(number)

EXAMPLE =>

a = Int(99.8) ' Returns 99.

a = Fix(99.2) ' Returns 99.

b = Int(-99.8) ' Returns -100.

b = Fix(-99.8) ' Returns -99.

c = Int(-99.2) ' Returns -100.

c = Fix(-99.2) ' Returns -99.

HEX:-

Returns a String representing the hexadecimal value of a number.

SYNTAX =>

Hex(number)

EXAMPLE =>

a = Hex(5) ' Returns 5.

b = Hex(10) ' Returns A.

c = Hex(459) ' Returns 1CB.

Back to Content

Excel VBA Programming TYPE CHECK Functions

isArray:-

Returns a Boolean value indicating whether a variable is an array.

SYNTAX =>

IsArray(varname)

EXAMPLE =>

a (1 To 5) As Integer

b = Array(1, 2, 3)

c = IsArray(a) ' Returns True.

d = IsArray(b) ' Returns True.

isDate:-

Returns a Boolean value indicating whether an expression can be converted to a date.

SYNTAX =>

IsDate(expression)

EXAMPLE =>

a = "February 12, 1969"

b = #2/12/69#

c = "Hello"

d = IsDate(a) ' Returns True.

e = IsDate(b) ' Returns True.

f = IsDate(c) ' Returns False.

isEmpty:-

Returns a Boolean value indicating whether a variable has been initialized.

SYNTAX =>

IsEmpty(expression)

EXAMPLE =>

a = IsEmpty(r) ' Returns True.

b = Null

d = IsEmpty(b) ' Returns False.

c = Empty

e = IsEmpty(c) ' Returns True.

isNull:-

Returns a Boolean value that indicates whether an expression contains no valid data (Null).

SYNTAX =>

IsNull(expression)

EXAMPLE =>

a = IsNull (r) ' Returns False.

b = Null

d = IsNull (b) ' Returns True.

c = Empty

e = IsNull (c) ' Returns False.

isNumeric:-

Returns a Boolean value indicating whether an expression can be evaluated as a number.

SYNTAX =>

IsNumeric(expression)

EXAMPLE =>

a = IsNumeric (9) ' Returns True.

b = Null

d = IsNumeric (1.9) ' Returns True.

c = Empty

e = IsNumeric (“456 PINCODE) ' Returns False.

Back to Content

Excel VBA Conditional Statements

If...Then...Else Statements:- You can use the If..Then..Else statement to run a specific statement or a block of statements, depending

on the value of a condition.

If..Then..Else statements can be nested to as many levels as you need.

To run only one statement when a condition is True, use the single-line syntax of the If...Then...Else

statement. ->

If a = 1 Then C = d+2

To run more than one line of code, you must use the multiple-line syntax. This syntax includes the End If

statement. ->

If a = 1 Then

b = d + 2

c = d / 2

e = d * 2

End if

You can add ElseIf statements to an If...Then...Else statement to test a second condition if the first

condition is False. ->

If a = 1 Then

c = d + 2

ElseIf a = 2 Then

c = d / 2

Else

c = 0

End if

Select Case Statements:- Use the Select Case statement as an alternative to using ElseIf in If...Then...Else statements when

comparing one expression to several different values. ->

Select Case performance

Case 1

Bonus = salary * 0.1

Case 2, 3

Bonus = salary * 0.09

Case 4 To 6

Bonus = salary * 0.07

Case Is > 8

Bonus = 100

Case Else

Bonus = 0

End Select

Back to Content

Excel VBA Loops

While...Wend Statement:- Executes a series of statements as long as a given condition is True. - >

Counter = 0 ' Initialize variable.

While Counter < 20 ' Test value of Counter.

Counter = Counter + 1 ' Increment Counter.

Wend ' End While loop when Counter > 19.

Do...Loop Statements:- You can use Do...Loop statements to run a block of statements an indefinite number of times. The

statements are repeated either while a condition is True or until a condition becomes True. ->

SYNTAX =>

Do [{While | Until} condition]

[statements]

[Exit Do]

[statements]

Loop

EXAMPLE =>

counter = 0

myNum = 20

Do While myNum > 10

myNum = myNum - 1

counter = counter + 1

Loop

SYNTAX =>

Do

[statements]

[Exit Do]

[statements]

Loop [{While | Until} condition]

EXAMPLE =>

counter = 0

myNum = 1

Do

myNum = myNum + 1

counter = counter + 1

Loop Until myNum = 10

For...Next Statement:- Repeats a group of statements a specified number of times. ->

SYNTAX =>

For counter = start To end [Step step]

[statements]

[Exit For]

[statements]

Next [counter]

EXAMPLE =>

For I = 1 To 10

For J = 1 To 10

For K = 1 To 10

...

Next K

Next J

Next I

EXAMPLE =>

For I = 10 To 11 Step -1

...

Next I

For Each...Next Statement:- Repeats a group of statements for each element in an array or collection. ->

SYNTAX =>

For Each element In group

[statements]

[Exit For]

[statements]

Next [element]

EXAMPLE =>

For Each oFile in oFiles

...

Next

With Statement:- Executes a series of statements on a single object or a user-defined type. ->

SYNTAX =>

With Object

[statements]

End With

EXAMPLE =>

With MyLabel

.Height = 2000

.Width = 2000

.Caption = "This is MyLabel"

End With

Back to Content

Error Handling

When VBA encounters an error and you have no error-checking code in place, the program stops and

presents you with “continue, End, Debug, Help” error message i.e. Run-time error.

On Error GoTo:-

The basic error-handling option is to tell VBA that in the case of an error you want to have code branch

to a specific area of the macro.

A typical scenario is to add the error-handling routine at the end of the macro:

1) After the last code line of the macro, insert the code line Exit sub.

2) After the Exit Sub line, add a label. A label is name followed by colon. For example, you might

create a label called MyErrorHandler:

3) Write the code to handle the error. If you want to return control of the macro to the line after

the one that caused the error, use the statement Resume Next.

EXAMPLE =>

Generic Error Handler ->

On Error Goto HandleAny

Sheet(9).Select

Exit Sub

HandleAny:

Msg = “We encountered “ & Err.Number & “-“ & Err.Description

Msgbox Msg

Ignoring Errors ->

MyFile = “filename”

On Error Resume Next

Workbooks.Open MyFile

On Error Goto 0

Below are the Common Run-time Errors which are encountered –

1) Runtime Error 9:Subscript Out Of Range

The Runtime Error 9 is often caused when you expect a worksheet to be there and it has been

deleted or renamed by the user / client.

2) Runtime Error 1004: Method Range of Object Global Failed

The Runtime Error 1004 can be caused by a number of things.

Back to Content

Excel VBA Short-Cuts

Description Short-Cut Keys

VBA <-> Access Alt+F11

Property List Ctrl+J

Constant List Ctrl+Shift+J

Quick Info Ctrl + I

Parameter Info Ctrl+Shift+I

Immediate Ctrl +G

Run F5

Step Into F8

Step Over Shift+F8

Break Loop Ctrl+Break

Object Browser F2

Close VBA Alt+F4

In Form user mode F5

Design Mode Alt+V+Enter

Close Form Ctrl+F4

Open Properties Alt+Enter

Complete Word Ctrl+Space

Project Explorer Ctrl+R

Properties Window F4

Toggle Breakpoint F9

Clear All Breakpoint Ctrl+Shift+F9

Quick Watch Shift+F9

Run to Cursor Ctrl+F8

Reference Alt+T+R

Module Alt+I+M

Procedure Alt+I+P

User Form Alt+I+U

Class Module Alt+I+C

Switch Split Windows F6

View Code Window F7

Activate Menu bar F10

Go to Last Position Ctrl+Shift+F2

Step Out Ctrl+Shift+F8

Clear all breakpoints Ctrl+Shift+F9