LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï...

30
iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆμÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore 560 054 Email: [email protected] Website: www.itechanalytcisolutions.com Mobile: 9902058793

Transcript of LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï...

Page 1: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

iTech Analytic Solutions

LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì

No. 9, 1st Floor, 8th Main, 9th Cross,

SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054

Email: [email protected] Website: www.itechanalytcisolutions.com

Mobile: 9902058793

Page 2: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 2

VBA Codes

Simple VBA Examples

Page 3: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 3

Enable Macros in Excel

You can enable macros in Excel by setting your Excel Security Level:

Office 2000-2003:

Menu :: Tools :: Macros :: Security.

Office 2007:

Microsoft Office Button :: Excel Options :: Trust Center :: Center Settings :: Macro Settings.

You can set Security to High, Medium or Low:

High Security.

All Excel macros (except from trusted sources) are disabled.

Medium Security.

User is prompted on each file-open to enable or disable Excel macros.

Low Security.

Excel Macros can run automatically without a prompt. You are not protected from potentially unsafe

macros.

Page 4: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 4

Range Object in VBA

The Range Object is the object you will use most within your Excel VBA. Before you can manipulate any

region within Excel, you must express it as a Range object:

Dim myRange As Range

Set myRange = ActiveSheet.Range("A1")

and work with methods and properties of that range:

myRange.Delete Shift:=xlUp

A Range object represents a cell, a row, a column, a selection of cells containing one or more blocks of cells

or even a group of cells on multiple sheets:

' Cells

Set myRange = ActiveSheet.Range("A1:D5")

' Row

Set myRange = ActiveSheet.Rows(1)

' Column

Set myRange = ActiveSheet.Columns(2)

' Group of Cells

Set myRange = Application.Union( _

ActiveSheet.Range("A1:D1"), _

ActiveSheet.Range("C3:C5"))

' Select method

myRange.Select

Page 5: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 5

Using Intersection to Create a Range in Excel VBA

Intersect Method returns a Range object that represents the Intersection of Ranges.

Example selects the Intersection of 2 Ranges (A1:D5 and C3:C10). If the Intersection is blank, the example

displays a message box:

Private Sub UseIntersection()

IntersectRanges Range("A1:D5"), Range("C3:C10")

End Sub

Private Sub IntersectRanges(range1 As Range, range2 As Range)

Dim intRange As Range

' Application.Intersect Method

Set intRange = Application.Intersect(range1, range2)

If intRange Is Nothing Then

' No Intersection

MsgBox "Ranges Do Not Intersect!"

Else

' Show new Range's address

MsgBox (intRange.Address)

' Select new Range

intRange.Select

End If

End Sub

Page 6: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 6

Screen Updating using VBA in Excel

When you don't want to see your screen follow the actions of your VBA code (macro), you can

use ScreenUpdating property:

Application.ScreenUpdating

Use ScreenUpdating property to turn screen updating off to speed up your macro code:

Application.ScreenUpdating = False

You won't be able to see what the macro is doing, but it will run faster. When your macro ends don't forget to

set the ScreenUpdating property back to True.

Application.ScreenUpdating = True

Example:

' Add New Worksheet

Private Sub GenerateNewWorksheet()

Dim ActSheet As Worksheet

Dim NewSheet As Worksheet

' Prevents screen refreshing.

Application.ScreenUpdating = False

Set ActSheet = ActiveSheet

Set NewSheet = ThisWorkbook.Sheets().Add()

NewSheet.Move After:=Sheets(ThisWorkbook.Sheets().Count)

ActSheet.Select

' Enables screen refreshing.

Application.ScreenUpdating = True

End Sub

Page 7: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 7

Save Workbook as New File using VBA in Excel

Q. How Save Workbook as New File?

A. Use the following VBA code:

Private Sub SaveWorkbookAsNewFile(NewFileName As String)

Dim ActSheet As Worksheet

Dim ActBook As Workbook

Dim CurrentFile As String

Dim NewFileType As String

Dim NewFile As String

Application.ScreenUpdating = False ' Prevents screen refreshing.

CurrentFile = ThisWorkbook.FullName

NewFileType = "Excel Files 1997-2003 (*.xls), *.xls," & _

"Excel Files 2007 (*.xlsx), *.xlsx," & _

"All files (*.*), *.*"

NewFile = Application.GetSaveAsFilename( _

InitialFileName:=NewFileName, _

fileFilter:=NewFileType)

If NewFile <> "" And NewFile <> "False" Then

ActiveWorkbook.SaveAs Filename:= NewFile, _

FileFormat:=xlNormal, _

Password:="", _

WriteResPassword:="", _

ReadOnlyRecommended:=False, _

CreateBackup:=False

Set ActBook = ActiveWorkbook

Workbooks.Open CurrentFile

ActBook.Close

End If

Page 8: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 8

Application.ScreenUpdating = True

End Sub

How does it work? Let's look inside.

First, turn off screen updating:

Application.ScreenUpdating = False

Store the opened file full path:

CurrentFile = ThisWorkbook.FullName

Open window to choose new filename and folder:

NewFile = Application.GetSaveAsFilename( _

InitialFileName:=NewFileName, _

fileFilter:=NewFileType)

And now save file as new Workbook:

ActiveWorkbook.SaveAs Filename:= NewFile, _

FileFormat:=xlNormal, _

Password:="", _

WriteResPassword:="", _

ReadOnlyRecommended:=False, _

CreateBackup:=False

We have to close new file and open the origin workbook:

Set ActBook = ActiveWorkbook

Workbooks.Open CurrentFile

ActBook.Close

and turn on screen updating:

Application.ScreenUpdating = True

Page 9: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 9

Option Explicit Statement in VBA

Q. How to avoid incorrectly typing the name of an existing variable?

A. Use Option Explicit statement at file level to force explicit declaration of all variables in the script:

Option Explicit

Option Explicit statement must appear in a script before any procedures.

When you use the Option Explicit statement, you must explicitly declare all variables using

the Dim, Private, Public, or ReDim statements. If you attempt to use an undeclared variable name, an error

occurs:

Dim myVar

myVar = 1

myNewVar = 0 ' ERROR: Variable not defined.

Page 10: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 10

How To Store Current Range Selection using VBA in Excel?

Q. How To Store Current Selection using VBA in Excel?

A. Use the foloowing VBA script:

Option Explicit

Private Sub Example()

Dim ActSheet As Worksheet

Dim SelRange As Range

Set ActSheet = ActiveSheet

Set SelRange = Selection

'' Any code here

'Dim NewSheet As Worksheet

'

'ActiveSheet.Range("A1").Select

'

'Set NewSheet = ThisWorkbook.Sheets().Add()

'NewSheet.Move After:=Sheets(ThisWorkbook.Sheets().Count)

ActSheet.Select

SelRange.Select

End Sub

Let's discuss how it works. First, force explicit declaration of all variables:

Option Explicit

To store selection we need two variables (Worksheet and Range):

Dim ActSheet As Worksheet

Dim SelRange As Range

Then we store active Worksheet and current range selection:

Set ActSheet = ActiveSheet

Set SelRange = Selection

Now we can use any VBA code (add new sheets, select or hide cells etc) and then restore origin selection:

ActSheet.Select

SelRange.Select

Page 11: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 11

Using Message Box (MsgBox) in Excel VBA

MsgBox function in VBA displays a message in a window and waits for click on a button.

Example of using Yes-No Message Box:

Sub MessageBoxExample()

Dim iRet As Integer

Dim strPrompt As String

Dim strTitle As String

' Promt

strPrompt = "Ask Your Question Here, OK?"

' Dialog's Title

strTitle = "My Tite"

'Display MessageBox

iRet = MsgBox(strPrompt, vbYesNo, strTitle)

' Check pressed button

If iRet = vbNo Then

MsgBox "NO!"

Else

MsgBox "Yes!"

End If

End Sub

Message Box returns an integer value to indicate clicked button (Yes, No, Cancel, etc.):

Return Values

1 OK vbOk

2 Cancel vbCancel

3 Abort vbAbort

4 Retry vbRetry

5 Ignore vbIgnore

6 Yes vbYes

7 No vbNo

Page 12: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 12

You can specify the number and type of buttons of Message Box (the default value for buttons is 0 – display

OK button only):

Type of Buttons

0 vbOKOnly OK button only

1 vbOKCancel OK and Cancel buttons

2 vbAbortRetryIgnore Abort, Retry, and Ignore buttons

3 vbYesNoCancel Yes, No, and Cancel buttons

4 vbYesNo Yes and No buttons

5 vbRetryCancel Retry and Cancel buttons

Page 13: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 13

Define a Position of MessageBox using VBA in Excel

Typical MsgBox pops-up in the center of the screen. You can change MsgBox's position using a Hooking API

in your VBA code:

You must create a CBT hook

Run a Message Box with CBT hook

Catch a HCBT_ACTIVATE message in the Hook procedure

Set new position using the SetWindowPos function

Release the CBT hook

Example: Hooking MessageBox using VBA in Excel:

Option Explicit

' Import

Private Declare Function UnhookWindowsHookEx Lib "user32" _

(ByVal hHook As Long) As Long

Private Declare Function GetCurrentThreadId Lib "kernel32" () As Long

Private Declare Function SetWindowsHookEx Lib "user32" _

Alias "SetWindowsHookExA" _

(ByVal idHook As Long, _

ByVal lpfn As Long, _

ByVal hmod As Long, _

ByVal dwThreadId As Long) As Long

Private Declare Function SetWindowPos Lib "user32" _

(ByVal hwnd As Long, _

ByVal hWndInsertAfter As Long, _

ByVal x As Long, _

ByVal y As Long, _

ByVal cx As Long, _

ByVal cy As Long, _

ByVal wFlags As Long) As Long

' Handle to the Hook procedure

Private hHook As Long

Page 14: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 14

' Position

Private msgbox_x As Long

Private msgbox_y As Long

' Hook type

Private Const WH_CBT = 5

Private Const HCBT_ACTIVATE = 5

' SetWindowPos Flags

Private Const SWP_NOSIZE = &H1 ' Retains the current size

Private Const SWP_NOZORDER = &H4 ' Retains the current Z order

Sub TestMsgBox()

MsgBoxPos "Set non-Center Position", _

vbOKOnly, _

"Message Box Hooking", _

400, 300

End Sub

Public Sub MsgBoxPos(strPromt As String, _

vbButtons As VbMsgBoxStyle, _

strTitle As String, _

xPos As Long, _

yPos As Long)

' Store position

msgbox_x = xPos

msgbox_y = yPos

' Set Hook

hHook = SetWindowsHookEx(WH_CBT, _

AddressOf MsgBoxHookProc, _

0, _

GetCurrentThreadId)

Page 15: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 15

' Run MessageBox

MsgBox strPromt, vbButtons, strTitle

End Sub

Private Function MsgBoxHookProc(ByVal lMsg As Long, _

ByVal wParam As Long, _

ByVal lParam As Long) As Long

If lMsg = HCBT_ACTIVATE Then

' Change position

SetWindowPos wParam, 0, msgbox_x, msgbox_y, _

0, 0, SWP_NOSIZE + SWP_NOZORDER

' Release the Hook

UnhookWindowsHookEx hHook

End If

MsgBoxHookProc = False

End Function

Page 16: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 16

Custom Message Box Buttons using Hooking in Excel VBA

Q. How can I change the button caption for the Message Box (MsgBox)?

A. You need to use Windows Hooking API in your Excel VBA:

You must create a CBT hook

Run a Message Box with CBT hook

Catch a HCBT_ACTIVATE message in the Hook procedure

Set new cputions for the buttons using the SetDlgItemText function

(example below changes “Yes” and “No” captions to smiles: “:-)” and “:-(” )

Release the CBT hook

Example: Change Button Captions for Message Box using VBA in Excel:

Option Explicit

' Import

Private Declare Function GetCurrentThreadId Lib "kernel32" () As Long

Private Declare Function SetDlgItemText Lib "user32" _

Alias "SetDlgItemTextA" _

(ByVal hDlg As Long, _

ByVal nIDDlgItem As Long, _

ByVal lpString As String) As Long

Private Declare Function SetWindowsHookEx Lib "user32" _

Alias "SetWindowsHookExA" _

(ByVal idHook As Long, _

ByVal lpfn As Long, _

ByVal hmod As Long, _

ByVal dwThreadId As Long) As Long

Private Declare Function UnhookWindowsHookEx Lib "user32" _

(ByVal hHook As Long) As Long

' Handle to the Hook procedure

Private hHook As Long

' Hook type

Page 17: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 17

Private Const WH_CBT = 5

Private Const HCBT_ACTIVATE = 5

' Constants

Public Const IDOK = 1

Public Const IDCANCEL = 2

Public Const IDABORT = 3

Public Const IDRETRY = 4

Public Const IDIGNORE = 5

Public Const IDYES = 6

Public Const IDNO = 7

Public Sub MsgBoxSmile()

' Set Hook

hHook = SetWindowsHookEx(WH_CBT, _

AddressOf MsgBoxHookProc, _

0, _

GetCurrentThreadId)

' Run MessageBox

MsgBox "Smiling Message Box", vbYesNo, "Message Box Hooking"

End Sub

Private Function MsgBoxHookProc(ByVal lMsg As Long, _

ByVal wParam As Long, _

ByVal lParam As Long) As Long

If lMsg = HCBT_ACTIVATE Then

SetDlgItemText wParam, IDYES, ":-)"

SetDlgItemText wParam, IDNO, ":-("

' Release the Hook

UnhookWindowsHookEx hHook

End If

Page 18: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 18

MsgBoxHookProc = False

End Function

Page 19: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 19

Custom Message Box Buttons using Hooking in Excel VBA

Q. How can I change the button caption for the Message Box (MsgBox)?

A. You need to use Windows Hooking API in your Excel VBA:

You must create a CBT hook

Run a Message Box with CBT hook

Catch a HCBT_ACTIVATE message in the Hook procedure

Set new cputions for the buttons using the SetDlgItemText function

(example below changes “Yes” and “No” captions to smiles: “:-)” and “:-(” )

Release the CBT hook

Example: Change Button Captions for Message Box using VBA in Excel:

Option Explicit

' Import

Private Declare Function GetCurrentThreadId Lib "kernel32" () As Long

Private Declare Function SetDlgItemText Lib "user32" _

Alias "SetDlgItemTextA" _

(ByVal hDlg As Long, _

ByVal nIDDlgItem As Long, _

ByVal lpString As String) As Long

Private Declare Function SetWindowsHookEx Lib "user32" _

Alias "SetWindowsHookExA" _

(ByVal idHook As Long, _

ByVal lpfn As Long, _

ByVal hmod As Long, _

ByVal dwThreadId As Long) As Long

Private Declare Function UnhookWindowsHookEx Lib "user32" _

(ByVal hHook As Long) As Long

' Handle to the Hook procedure

Private hHook As Long

' Hook type

Page 20: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 20

Private Const WH_CBT = 5

Private Const HCBT_ACTIVATE = 5

' Constants

Public Const IDOK = 1

Public Const IDCANCEL = 2

Public Const IDABORT = 3

Public Const IDRETRY = 4

Public Const IDIGNORE = 5

Public Const IDYES = 6

Public Const IDNO = 7

Public Sub MsgBoxSmile()

' Set Hook

hHook = SetWindowsHookEx(WH_CBT, _

AddressOf MsgBoxHookProc, _

0, _

GetCurrentThreadId)

' Run MessageBox

MsgBox "Smiling Message Box", vbYesNo, "Message Box Hooking"

End Sub

Private Function MsgBoxHookProc(ByVal lMsg As Long, _

ByVal wParam As Long, _

ByVal lParam As Long) As Long

If lMsg = HCBT_ACTIVATE Then

SetDlgItemText wParam, IDYES, ":-)"

SetDlgItemText wParam, IDNO, ":-("

' Release the Hook

UnhookWindowsHookEx hHook

End If

Page 21: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 21

MsgBoxHookProc = False

End Function

Page 22: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 22

Using InputBox Method in Excel VBA

You can recieve a simple information from user using Message Box in your Excel VBA

code: Yes / No / Cancel etc.

But to gather more specific information (formula, number, text, logical value or cell reference) from a user you

need Application.InputBox method:

InputBox(Prompt[,Title][,Default][,x][,y][,HelpFile][,HelpContextId][,Type])

where Type specifies the return data type:

Type Values

0 Formula

1 Number

2 Text (String)

4 Logical value (True or False)

8 Cell reference (Range object)

16 Error value

64 Array of values

Example: Using InputBox method in Excel

Sub TestInputBox()

Dim myRange As Range

Set myRange = Application.InputBox(Prompt:= _

"Please Select a Range", _

Title:="InputBox Method", Type:=8)

If myRange Is Nothing Then

' Range is blank

Else

myRange.Select

End If

End Sub

Page 23: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 23

Bit Operations in Visual Basic (Excel VBA)

Each bit has value 0 or 1, all data is stored as a series of bits. Bits are grouped together to form bytes (8 bits)

and larger data elements:

Byte – 8 bits grouped into 1 byte

Integer – 16 bits (2 bytes)

Long – 32 bits (4 bytes)

For example, let's convert the binary number 11010001 to decimal. We need the powers of 2 from 0 (right bit)

to 7 (left bit): 20 = 1, 2

1 = 2, 2

2 = 4, … 2

7 = 128. So the example, binary number 110100012 is equal to:

110100012 = 128*1 + 64*1 + 32*0 + 16*1 + 8*0 + 4*0 + 2*0 + 1*1 = 209

The AND, OR, XOR and NOT operators are bit operations, they work on individual bits in a number. Except

for NOT (inverse) bit operators require 2 arguments also called operands.

Bit Operation OR

Bitwise operator OR check if either the right operand or the left operand is true, or if they are both true. In

other words, operation OR returns 1 in all cases except where the corresponding bits of both operands are

zero.

Bit 0 Bit 1 OR

0 0 0

0 1 1

1 0 1

1 1 1

' Example

' Bit operator OR

i = 81 Or 22

' i = 87 = 1010111 = 1010001 Or 10110

Bit Operation AND

Bitwise operator AND check if either the right operand and the left operand is true. In other words, operation

AND returns zero in all cases except where the corresponding bits of both operands are 1.

Bit 0 Bit 1 AND

0 0 0

0 1 0

1 0 0

Page 24: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 24

1 1 1

' Example

' Bit operator AND

i = 81 And 22

' i = 16 = 10000 = 1010001 And 10110

Bit Operation XOR

Bitwise operator XOR (or exclusive OR) sets the bit to 1 if the two bits are different, and 0 if they are the

same.

Bit 0 Bit 1 XOR

0 0 0

0 1 1

1 0 1

1 1 0

' Example

' Bit operator XOR

i = 81 Xor 22

' i = 71 = 1000111 = 1010001 Xor 10110

Bit Operation NOT

Bitwise operator NOT only takes a single argument and simply reverses all bits, changing all the ones to

zeros and zeros to ones.

' Example

' Bit operator NOT

i = Not 81

' i = 174 = 10101110 = Not 1010001

Page 25: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 25

Bit Shifting Function in Visual Basic (Excel VBA)

Do you need Bitwise Shift operators in Excel VBA (similar to “<<" and ">>” operators in C++)? Unfortunately,

VBA doesn't have any bit shift operators. But we can replicate bitwise shift operators with multiplying or

dividing by the appropriate power of 2.

Bitwise Right Shift Function:

Public Function shr(ByVal Value As Long, ByVal Shift As Byte) As Long

Dim i As Byte

shr = Value

If Shift > 0 Then

shr = Int(shr / (2 ^ Shift))

End If

End Function

Right shifting is equal to dividing Value by 2Shift

.

Bitwise Left Shift Function:

Public Function shl(ByVal Value As Long, ByVal Shift As Byte) As Long

shl = Value

If Shift > 0 Then

Dim i As Byte

Dim m As Long

For i = 1 To Shift

m = shl And &H40000000

shl = (shl And &H3FFFFFFF) * 2

If m <> 0 Then

shl = shl Or &H80000000

End If

Next i

End If

End Function

Left shifting is equal to multiplying Value by 2Shift

. But to avoid an overflow error we use small trick:

m = shl And &H40000000 ' save 30th bit

shl = shl And &H3FFFFFFF ' clear 30th and 31st bits

shl = shl * 2 ' multiply by 2

Page 26: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 26

If m <> 0 Then

shl = shl Or &H80000000 ' set 31st bit

End If

Page 27: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 27

Disable Alert (Warning) Messages in Excel

Sometimes the Excel displays a message asking if you want to continue, for example:

Do you want to save a file before closing?

Data may exist in the sheet(s) selected for deletion. To permanently delete the data, press Delete.

These alerts can be turned off by using this VBA-code:

Application.DisplayAlerts = False

After a routine you must turn on alert messages:

Application.DisplayAlerts = True

Page 28: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 28

Description VBA Code

Selecting '==Select 3 rows down, 2 columns right: ActiveCell.Offset(3, 2).Select

'==Select from active cell to last row of list: Range(Selection, Selection.End(xlDown)).Select

'==Select from current cell to last column of list: Range(Selection, Selection.End(xlToRight)).Select

'==Select last cell of worksheet: Selection.SpecialCells(xlLastCell).Select

Pasting '==Paste formula value, not formula: Range("A3").Copy Range("D26").PasteSpecial Paste:=xlValues

'==Paste into a cell and move its original contents to the next cell: Selection.Insert Shift:=xlToRight

Columns and Rows

'==Hide a column: Selection.EntireColumn.Hidden = True

'==Insert a column: Columns("N:N").Insert

'==Delete columns: Columns("B:E").EntireColumn.Delete

'==Insert a new row at current cell: Selection.EntireRow.Insert

'==Delete row of current cell: Selection.EntireRow.Delete

'==Set column width: Selection.EntireColumn.ColumnWidth = 10

'==Set row height: Selection.RowHeight = 26.25

'==Set row height to size of contents: Selection.Rows.AutoFit

Page 29: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 29

Description VBA Code

Cell Formatting '==Text not wrapped: Selection.WrapText = False

'==Remove color: Selection.Interior.ColorIndex = xlNone

'==Set font size: Selection.Font.Size = 8

'==Date and time format: Selection.NumberFormat = "mm-dd-yyyy hh:mm AM/PM"

'==Number format with comma: Selection.NumberFormat = "#,##0"

'==Left aligned: Selection.HorizontalAlignment = xlLeft

'==Bottom aligned: Selection.VerticalAlignment = xlBottom

'==Indented text: Selection.IndentLevel = 3

'==Delete contents but not formatting: Selection.ClearContents

'==Delete contents and formatting: Selection.Clear

Display '==Hide activity while macro runs: Application.ScreenUpdating = False

'==Turn off automatic alerts: Application.DisplayAlerts = False

'==Freeze panes: ActiveWindow.FreezePanes = True

'==Show how long macro runs: Dim strTime1 as String, strTime2 as String strTime1 = Format(Now(), "mm-dd-yyyy hh:MM:ss")

[put other macro code here] strTime2 = Format(Now(), "mm-dd-yyyy hh:MM:ss") MsgBox "Elapsed Time = " & DateDiff("n", strTime1, strTime2)

Page 30: LmÉPï C£Á°nPï ¸À®ÆµÀ£ï쀦 · iTech Analytic Solutions LmÉPï C£Á°nPï ¸À®ÆµÀ£ïì No. 9, 1st Floor, 8th Main, 9th Cross, SBM Colony, Brindavan Nagar,

No. 9, 1st Floor, 8

th Main, 9

th Cross, SBM Colony, Brindavan Nagar, Mathikere, Bangalore – 560 054 Page: 30

Description VBA Code

Range Names '==Add a range name: ActiveWorkbook.Names.Add Name:="Groups", RefersTo:=Selection

'==Go to a named range: Range("Groups").Select

'==Delete all range names in workbook: Dim n as Object For Each n In ActiveWorkbook.Names

n.Delete Next

Path/File Name '==Insert path/file name into a cell: ActiveCell.Value = ActiveWorkbook.FullName

'==Insert path/file name into a footer: ActiveSheet.PageSetup.CenterFooter = ActiveWorkbook.FullName

Pivot Tables '===Remove unused items in pivot tables when data has changed: Dim pt As PivotTable, ws As Worksheet For Each ws In ActiveWorkbook.Worksheets

For Each pt In ws.PivotTables pt.PivotCache.MissingItemsLimit = xlMissingItemsNone

Next pt Next ws

Worksheets '==Add date to title of each worksheet: Dim sht As Worksheet For Each sht In ActiveWorkbook.Worksheets

sht.Select Range("A1").Value = Range("A1").Value & " through " & strDate

Next sht