Sunday, March 31, 2013

How to Export or Save Each Sheet as Tab Delimited Text File with VBA Macro

Excel VBA Macro to Export or Save Each Sheet as Tab Delimited Text File with Back Up
'This Macro Creates a Folder With Workbook Name & Date Stamp and Saves Each Worksheet as a Tab Delimited Text File and Keep a Copy of Excel Sheet as Back up In Target Folder
Sub Export_Each_Sheet_As_TabDelimited_TextFile()
Dim WS As Worksheet
Dim MyStr1 As String
Dim MyStr2 As String
Dim MyPath As String
Dim SavePath As String
Dim MyDate
Dim MyTime

MyDate = Date    ' MyDate Returns the current system date.

MyTime = Time    ' Returns current system time.

Application.DisplayAlerts = False

Application.ScreenUpdating = False
On Error Resume Next

MyStr1 = Format(MyDate, "DD-MM-YYYY")

'Use MyStr2 If You Require Time Stamp In File Name
'MyStr2 = Format(MyTime, "HH.MM.SS")
MyPath = "C:\Documents and Settings\Administrator\My Documents\"
MkDir MyPath & MyStr1 & "_" & ThisWorkbook.Name
SavePath = MyPath & MyStr1 & "_" & ThisWorkbook.Name & "\"

For Each WS In ThisWorkbook.Sheets

WS.Activate
ActiveSheet.Copy
'Exporting Sheet as Tab Delimited Text File To Target Path
ActiveSheet.SaveAs Filename:=SavePath & WS.Name, FileFormat:=xlTextWindows
'Saving a Backup Copy of a Sheet in Target Path
ActiveSheet.SaveAs Filename:=SavePath & WS.Name, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close Savechanges:=True
Next WS
Application.DisplayAlerts = True
Application.ScreenUpdating = True
ThisWorkbook.Activate
'ThisWorkbook.Close Savechanges:=True
'Application.Quit
End Sub

--------------------------------------------------------------------------------------------------------
Thanks, TAMATAM ; Business Intelligence & Analytics Professional
--------------------------------------------------------------------------------------------------------

Tuesday, March 26, 2013

How to Remove Duplicates from Multiple Columns using Excel VBA Macro

Excel Macro to Remove Duplicates from Each Column In a Active Sheet
Sub Remove_Dups_In_All_Columns()
Dim X As Integer
Dim Y As Integer
Dim CC As Long
Dim DC As Integer

DC = 0

CC = ActiveSheet.Columns.count

For X = 1 To CC 'Count of All Columns In Active Sheet
If Cells(1, X) = "" Then Exit For
DC = DC + 1 'Data Columns Count In Active Sheet
Next X

For Y = 1 To DC

ActiveSheet.Cells(1, Y).EntireColumn.Select
Selection.RemoveDuplicates Columns:=1, Header:=xlYes
Next Y

End Sub


Thanks,
TAMATAM



How to Combine or Merge or Consolidate Data from Multiple Columns Into a Dynamic Column and Remove Duplicates

Excel VBA Macro To Combine or Merge or Consolidate Data From Multiple Columns into a Dynamic Column and Remove Duplicates
This is a very user friendly macro that Search for a Dynamic Column and Consolidate the data from multiple columns into a Dynamic Column and shows the Unique data in the Next Column.
Sub Consol_Get_Unique()
Dim I As Integer
Dim J As Integer
Dim TC As Long
Dim Col_Search As String
Dim TargetColumn As Range

Col_Search = "Consol_Data" 'Dynamic Column Name In Which We Consolidate Data


Set TargetColumn = ActiveSheet.Rows(1).Find(What:=Col_Search, LookIn:=xlValues, _

    LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)

If Not TargetColumn Is Nothing Then

        MsgBox "Target Column Found At  " & TargetColumn.Address & _
        " and the Targe Column Number is " & TargetColumn.Column
Else:
MsgBox "TargetColumn Not Found"
End If

TC = TargetColumn.Column

Uniq_Data = TC + 1 'Unique Data Column Is Next To Consol Data Column

Z = 1 'Counting Variable

For I = 1 To 4 'Columns having data
For J = 2 To 100 'Rows having data
If Cells(J, I) = "" Then Exit For
Z = Z + 1
Cells(Z, TC) = Cells(J, I) 'Dynamic Column In Which We Consoldate Data
Next J
Next I

ActiveSheet.Columns(TC).Select

Selection.Copy
ActiveSheet.Columns(Uniq_Data).Select
ActiveSheet.Paste
Range(Selection, Selection.End(xlDown)).RemoveDuplicates Columns:=1, Header:=xlYes
ActiveSheet.Cells(1, Uniq_Data) = "Unique_Data"
Application.CutCopyMode = False

End 


Thanks.,Tamatam

How To Search in a Dynamic Column in Excel

Excel VBA Macro To Find a Dynamic Column Name
Sub Dynamic_Column_Search()
Dim Col_Search As String
Dim TargetColumn As Range

Col_Search = "Consol_Data" 'Dynamic Column Name That you want Search or Find

Set TargetColumn = ActiveSheet.Rows(1).Find(What:=Col_Search, LookIn:=xlValues, _

    LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)

If Not TargetColumn Is Nothing Then

        MsgBox "Target Column Found At  " & TargetColumn.Address & _
        " and the Targe Column Number is " & TargetColumn.Column
Else:
MsgBox "TargetColumn Not Found"
End If
End Sub

Saturday, March 23, 2013

How To Combine or Merge or Consolidate or Import or Export Data From Multiple Workbooks Into One Sheet

Excel VBA Macro To Combine or Merge or Consolidate or Import or Export Data from All Sheets of  Multiple Workbooks Into Single Sheet of Another New Workbook

Sub Consol_All_Books2OneSheet()
Dim LastDataRow As Long
Dim LastDataColumn As Long
Dim MyDataRange As Object
Dim WS As Worksheet
Dim DataSource As String

On Error Resume Next

Application.ScreenUpdating = False
Application.EnableEvents = False
Application.DisplayAlerts = False
On Error Resume Next

Export2File = Format(Now(), " DD_MM_YYYY HH-MM AMPM ")


'Target File location into which files are to be Merge.....Change as you wish.......

Workbooks.Add(xlWBATWorksheet).SaveAs FileName:="D:\MBA\" & Export2File & ".xlsm ", FileFormat:=52
'FileFormat:=xlOpenXMLWorkbookMacroEnabled
    
Set TargetFile = ActiveWorkbook
ActiveWorkbook.Sheets(1).Name = "Consolidate"

'Source File location from which files are to be Export.....Change as you wish.......

SourcePath = "C:\Documents and Settings\Administrator\My Documents\"
SrcFileName = Dir(SourcePath & "*.xls*")
    
Do While SrcFileName <> ""
Set SourceFile = Workbooks.Open(FolderPath & SrcFileName)
'With SourceFile 
   ' .UpdateLinks = xlUpdateLinksNever 'never update links
   ' .UpdateRemoteReferences = False 'never update remote workbook

'End With

For Each WS In SourceFile.Sheets
WS.Activate

DataSource = "Source: [" & "Workbook Name:" & " " & ActiveWorkbook.Name & " " & _

"|" & "Sheet Name:" & " " & WS.Name & "|" & "Path :" & " " & ThisWorkbook.Path & "]"

LastDataRow = ActiveSheet.Cells.Find(what:="*", SearchOrder:=xlByRows, _

SearchDirection:=xlPrevious).Row

LastDataColumn = ActiveSheet.Cells.Find(what:="*", SearchOrder:=xlByColumns, _

SearchDirection:=xlPrevious).Column

Set MyDataRange = ActiveSheet.Range(Cells(1, 1).Offset(LastDataRow, 0), Cells(1, 1).Offset(0, LastDataColumn))

MyDataRange.Copy

TargetFile.Sheets("Consolidate").Activate

TargetDataRow = ActiveSheet.Cells.Find(what:="*", SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row

If TargetDataRow = "" Then

Cells(2, 1).Select
ActiveSheet.Paste
Cells(1, 1).Value = DataSource
Cells(1, 1).Font.Bold = True
Else:
Cells(TargetDataRow, 1).Offset(3, 0).Select
ActiveSheet.Paste
Cells(TargetDataRow, 1).Offset(2, 0).Value = DataSource
Cells(TargetDataRow, 1).Offset(2, 0).Font.Bold = True
End If

Next WS

SourceFile.Activate
ActiveWorkbook.Close SaveChanges:=False
    
SrcFileName = Dir() 'Allows to Go to Next File in a Directory
Loop

TargetFile.Close SaveChanges:=True

    
Application.EnableEvents = True
Application.DisplayAlerts = True
    
MsgBox "All Wokbooks with All Sheets Successfllly Exported To Target File Sheet", vbInformation, "Successfully Exported !"
End Sub


-------------------------------------------------------------------------------------------------------
Thanks, TAMATAM ; Business Intelligence & Analytics Professional
--------------------------------------------------------------------------------------------------------

How to Combine or Consolidate or Merge All Sheets Data Into One Sheet with VBA Macro

Excel VBA Macro to Combine or Merge or Consolidate All Sheets Data into One Sheet
'This is a very use full and User-friendly Macro which Copies the Active Data Range from Each sheet Into One Sheet[Consolidate].
Sub Consol_Sheets()
Dim LastDataRow As Long
Dim LastDataColumn As Long
Dim MyDataRange As Object
Dim WS As Worksheet
Dim DataSource As String

On Error Resume Next

Application.ScreenUpdating = False
Application.EnableEvents = False

For Each WS In ThisWorkbook.Sheets

If WS.Name <> Sheets("Consolidate").Name Then
WS.Activate

DataSource = "Source: [" & "Workbook Name:" & " " & ActiveWorkbook.Name & " " & _

"|" & "Sheet Name:" & " " & WS.Name & "|" & "Path :" & " " & ThisWorkbook.Path & "]"

LastDataRow = ActiveSheet.Cells.Find(what:="*", SearchOrder:=xlByRows, _

SearchDirection:=xlPrevious).Row

LastDataColumn = ActiveSheet.Cells.Find(what:="*", SearchOrder:=xlByColumns, _

SearchDirection:=xlPrevious).Column

Set MyDataRange = ActiveSheet.Range(Cells(1, 1).Offset(LastDataRow, 0), Cells(1, 1).Offset(0, LastDataColumn))


MyDataRange.Copy

ThisWorkbook.Sheets("Consolidate").Activate

TargetDataRow = ActiveSheet.Cells.Find(what:="*", SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row

If TargetDataRow = "" Then Cells(2, 1).Select

ActiveSheet.Paste
Cells(1, 1).Value = DataSource
Cells(1, 1).Font.Bold = True
Else
Cells(TargetDataRow, 1).Offset(3, 0).Select
ActiveSheet.Paste
Cells(TargetDataRow, 1).Offset(2, 0).Value = DataSource
Cells(TargetDataRow, 1).Offset(2, 0).Font.Bold = True
End If

End If

Next WS

End Sub


Note:

We can perform the same task purely using Loops.To know that method please go through following link.
Consolidate All Sheets Data Into One Sheet Using Loops

Thanks,Tamatam

How to Find Active Workbook Full Path Name in VBA

How to Know the Active Workbook Full Path Name with VBA Macro
Sub WorkBook_Details()
ActivWorkbookPath = ActiveWorkbook.Path
ActiveWorkBookName = ActiveWorkbook.Name
ActWorkBookFullName = Application.ActiveWorkbook.FullName

MsgBox "ActiveWorkBookName = " & ActiveWorkBookName & vbCrLf & _

"ActivWorkbookPath = " & ActiveWorkbook.Path & vbCrLf & _
"ActWorkBookFullName =" & Application.ActiveWorkbook.FullName, vbInformation,
 "Work Book Details"
End Sub

Thanks,Tamatam

Friday, March 22, 2013

How to Add a Workbook with Single Sheet

Excel VBA Macro to Add a Workbook with Single Sheet
Sub WbkWithSingleSheet()
Workbooks.Add(xlWBATWorksheet).SaveAs _
FileName:="C:\Documents and Settings\Administrator\My Documents\Sample", _
FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub

'You can change your File Path which is colored above.

Thanks Tamatam

How To Consolidate or Merge or Import Multiple Workbooks into One Workbook with Excel VBA Macro

Excel VBA Macro To Import or Export Multiple Workbooks into One Workbook
Excel VBA Macro To Merge Multiple Workbooks with Multiple Sheets into One Workbook
'This is a very user friendly macro that allows you Merge all work sheets of multiple workbooks from a folder/location in to a Newly created Workbook in other location.

Sub MergeAllWorkbooks()


    Dim SourcePath As String
    Dim SrcFileName As String
    
    Dim SourceFile As Workbook
    Dim TargetFile As Workbook
    Dim WS As Worksheet
   
    Dim SheetIndex As Integer
    Dim Export2File As String
    
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.DisplayAlerts = False
    
    SheetIndex = 1    
    Export2File = Format(Now(), " DD_MM_YYYY HH-MM AMPM ")

Target File location in to which files are to be Merge.....Change as you wish.......
    Workbooks.Add.SaveAs FileName:="D:\TPR\Merge\" & Export2File & ".xlsm ", FileFormat:=52
    'FileFormat:=xlOpenXMLWorkbookMacroEnabled
    
    Set TargetFile = ActiveWorkbook
    
'Path From which Files are to be Merge........Change as you wish........
    SourcePath = "C:\Documents and Settings\Administrator\My Documents\"
    SrcFileName = Dir(SourcePath & "*.xls*")
    
    Do While SrcFileName <> ""
        Set SourceFile = Workbooks.Open(FolderPath & SrcFileName)
           
            For Each WS In SourceFile.Sheets 'Loop Through Each Worksheet
                WS.Copy Before:=TargetFile.Sheets(SheetIndex)
                SheetIndex = SheetIndex + 1
            Next WS
      
        SourceFile.Activate
        ActiveWorkbook.Close SaveChanges:=False
    
     SrcFileName = Dir() 'Allows to Go to Next File in a Directory
    Loop

    TargetFile.Close SaveChanges:=True

    
    Application.EnableEvents = True
    Application.DisplayAlerts = True
    
    MsgBox "All Wokbooks with All Sheets Successfllly Exported To Target File"
       
End Sub


--------------------------------------------------------------------------------------------------------
Thanks, TAMATAM ; Business Intelligence & Analytics Professional
--------------------------------------------------------------------------------------------------------

Wednesday, March 20, 2013

How to Find Current Region,Used Range,Last Row and Last Column in Excel with VBA Macro

Excel VBA Macros to Know Current Region, Used Range, Last Row, Last Column and Last Cell 
Macro To Select Current Region:
Sub CurrentRegion()
ActiveSheet.Range("a1").Select
ActiveCell.CurrentRegion.Select
End Sub
< or >
Sub Current_Region()
ActiveSheet.Cells.CurrentRegion.Select
End Sub



Note:
This Macro only selects current region where there is continuity in the range and ignores the remaining data in the sheet.
------------------------------------------------------------------------------------
Macro To Know Used Range In a ActiveSheet :
Model-1:
Sub UsedRange()
LastUsedRow = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row
LastUsedColumn = ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Column

' Last Row and Column based on Particular Column or Row :
' LastRow = Cells(Cells.Rows.Count,"A").End(xlUp).Row
' LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
' LastColumn = Cells(1, Cells.Columns.Count).End(xlToLeft).Column
' LastColumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column


MsgBox "You Have Used " & LastUsedRow & " Rows " & vbCrLf & _
" and " & LastUsedColumn & " Columns In This Worksheet"
End Sub

Model-II :
Sub Used_Rows_Columns_Range()
Dim RC As Long
Dim CC As Long
Dim Sort_Range As String

'To Get Column Index Number in Used Range(Eg: 1,2,3)
RC = ActiveSheet.UsedRange.Rows.Count
CC = ActiveSheet.UsedRange.Columns.Count
MsgBox RC
MsgBox CC

' To Get Column Index Name in Used Range(Eg: A,B,C..)
CN = Split(Cells(, CC).Address, "$")(1)
Data_Range = "$A$2" & " : " & "$" & CN & "$" & RC
MsgBox Data_Range


ActiveSheet.Range(Data_Range).Select
Selection.Copy

'To select the Last cell in the UsedRange
ActiveCell.SpecialCells(xlLastCell).Select

End Sub


Note:
This Macro show entire range or region that you have used in the past or  present in the active sheet even you may erases some cells data , they also comes under used range. 
------------------------------------------------------------------------------------
Macro To Select Last Used Cell In a Column Range :
Sub LastUsed_Column_Cell()
ActiveSheet.Range("A1").End(xlDown).Select
ActiveSheet.Range("A10000").End(xlUp).Select



End Sub

Note:
This Macro only selects current region in the column where there is continuity in the column range and ignores the remaining data in the column as shown in the above.

Other References for Dynamic Used Range :

How to Select Dynamic Actual Used Range in Excel


--------------------------------------------------------------------------------------------------------
Thanks, TAMATAM ; Business Intelligence & Analytics Professional 
--------------------------------------------------------------------------------------------------------

How to Find Last Used Row and Column in a Worksheet

Excel VBA Macro to Find Last Used Row and Column in a Worksheet
Sub LastRow_UsedInSheet()

MyLastRow = ActiveSheet.Cells.Find(what:="*", SearchOrder:=xlByRows, _

SearchDirection:=xlPrevious).Row

MyLastColumn = ActiveSheet.Cells.Find(what:="*", SearchOrder:=xlByColumns, _

SearchDirection:=xlPrevious).Column

MsgBox MyLastRow & " Rows Have Used In ActiveSheet " & vbCrLf & _

MyLastColumn & " Columns Have Used In ActiveSheet "

End Sub


Example :

Note:
This method will find only the Used Rows and Columns with data.
We can use this Count while Consolidating the data from the Several Sheets into One Sheet.

Thanks,TAMATAM

Saturday, March 16, 2013

How to Loop Through Each Column in Excel Sheet using VBA Macro

Excel VBA Macro To Paint the Column Walls Up to Empty Brick Found
'This macro Paints Column Wall upto it finds an Empty Cell/Brick ,When it finds an Empty Cell then it Moves to Next Column for Painting.
'We can use this Logic for several purposes in our Real Time Scenario's

Sub Jump2NextCol()
Dim X As Integer
Dim Y As Integer

For Y = 1 To 26 ' Colummns Having Data

For X = 1 To 500 ' Rows having data
If Cells(X, Y) <> "" Then
Cells(X, Y).Interior.ColorIndex = Y + 35 'Add colors
Else
GoTo NextCol:
End If
Next X
NextCol:
Next Y
End Sub



Thanks,
TAMATAM

How to use UPDATE Command in SQL Server

SQL Server UPDATE Command
The UPDATE is a DML command which is used to update existing records in a table, based on the condition specified in the Where Clause.
Syntax:
UPDATE Table_Name
SET Column1=Value1, Column2=Value2,...WHERE Some_Column=Some_Value

Example:

Let us consider the following 'Employee' Table.



Here from the above , we want to update the table by replacing the city "Hyderabad" with "Chennai". This can be done by using the following SQL Query.
UPDATE Employee SET City= 'Chennai" WHERE  City= 'Hyderabad"

Result:

Caution:
Be careful when updating records.If you omit the Where Clause in the above example then all the records in city column of the table are set to 'Chennai'.

Key Difference between Update and Alter Commands:

Update is a SQL command that is used to update existing records in a database, while Alter is a SQL command that is used to modify, delete or add a column to an existing table in a database.

Update is a DML statement whereas Alter is a DDL statement. Alter command modifies the database schema, while Update statement only modifies records in a database without modifying its structure.


Thanks,
TAMATAM

Friday, March 8, 2013

Excel VBA Objects,Methods and Properties

What are VBA Objects,Methods and Properties
Most programming languages deals with objects, a concept called object oriented programming. Excel VBA is not a truly object oriented programming language, but deal with objects.

----------------------------------------------------------------------
Objects : 
Objects are the fundamental building blocks of Visual Basic. An object is a special type of variable that contains both data and codes. A collection is a group of objects of the same class.
Workbooks is a collection of all Workbook objects.  Worksheets is a collection of Worksheet objects.

The Workbook object represents a workbook, the Worksheet object represents a worksheet, the Sheet object represents a worksheet or chartsheet, and the Range object represents a range of cells.

Example :
An Excel Worksheet is an object, cell in a worksheet is an object, range of cells is an object, font of a cell is an object, a command button is an object, and a text box is an object and more…
The following figure shows some objects:
How to refer Workbook and Worksheet Objects in VBA :
The workbook is the same as an Excel file.  The Workbook collection contains all the workbooks that are currently opened.  Inside of a workbook contains at least one worksheet.
In VBA, a worksheet can be referenced as followed:
Worksheets("Sheet3")
Worksheets("Sheet3") is the worksheet that named "Sheet3."Another way to refer to a worksheet is to use number index like the following:
Worksheets(3)
The above refers to the first worksheet in the collection.  
Remainder:
Worksheets(1) is not necessary the same sheet as Worksheets("Sheet1").
Sheets is a collection of worksheets and chart sheets.  A sheet can be indexed just like a worksheet.  Sheets(1) is the first sheet in the workbook.
To refer sheets (or other objects) with the same name, you have to qualify the object as follows
Workbooks("Book1").Worksheets("Sheet3")
Workbooks("Book2").Worksheets("Sheet3")

Range Object and Cells Property:
Range represents a cell, a row, a column, a selection of cells containing one or more contiguous blocks of cells, or a 3-D range. We will show you some examples on how Range object can be used.

The following example places text "AB" in range A1:B5, on Sheet2.
Worksheets("Sheet2").Range("A1:B5") = "AB"


Note that, Worksheets.Range("A1", "B5") = "AB" will yield the same result as the above example.The following place "AAA" on cell A1, A3, and A5 on Sheet2.
Worksheets("Sheet2").Range("A1, A3, A5") = "AAA"
Range object has a Cells property. This property is used in every VBA projects on this website (very important). The Cells property takes one or two indexes as its parameters. 
Example:
Cells(index) or Cells(row, column)

Here row is the row index and column is the column index.The following three statements are interchangeable:
ActiveSheet.Range.Cells(1,1)
Range.Cells(1,1)
Cells(1,1)


The following returns the same outcome:
Range("A1") = 123 and Cells(1,1) = 123
Range object has an Offset property that can be very handy when one wants to move the active cell around. The following examples demonstrate how the Offset property can be implemented (assume the current cell before the move is E5):

ActiveCell.Offset(1,0) = 1  'Place a "1" one row under E5 (on E6)
ActiveCell.Offset(0,1) = 1  'Place a "1" one column to the right of E5 (on F5)
ActiveCell.Offset(0,-3) = 1 'Place a "1" three columns to the left of E5 (on B5)

----------------------------------------------------------------------

METHODS and PROPERTIES:
Each object contains its own methods and properties.A Property represents a built-in or user-defined characteristic of the object. A method is an action that you perform with an object. Below are examples of a method and a property for the Workbook Object:

Workbooks.Close 
Close method close the active workbook
Workbooks.Count

Count property returns the number of workbooks that are currently opened.Some objects have default properties. For example, Range's default property is Value. 
The following yields the same outcome. 
Range("A1") = 1 and Range("A1").Value = 1

Set and to get a Range property value:
The following sets the value of range A1 or Cells(1,1) as "2005". It actually prints "2005" on A1.
Range("A1").Value = 2005
The following gets the value from range A1 or Cells(1,1).
X = Range("A1").Value
Method can be used with or without argument(s). 
Examples:
Methods That Take No Arguments:
Worksheets("Sheet").Column("A:B").AutoFit

Methods That Take Arguments:
Worksheets("Sheet1").Range("A1:A10").Sort
Worksheets("Sheet1").Range("A1")
Here the Range("A1:A10") is sort by Worksheets("Sheet1").Range("A1") is the Key (or column) .


Thanks, TAMATAM

Thursday, March 7, 2013

What are Workbook and Worksheet Events in Excel VBA

Excel VBA Events - Workbook and Worksheet Events
An Event is an action initiated either by user action or by other VBA code. An Event Procedure is a Sub procedure that you write, according to the specification of the event, that is called automatically by Excel when an event occurs.
The term 'Excel Events' refers to specific user actions within Excel. 

For example, if the user selects a Worksheet, enters data into a cell, or saves a Workbook, these actions are all Excel events.
Events are linked to Excel Worksheets, Charts, Workbooks, or to the Excel Application itself. Their purpose is to enable the programmer to create vba code to be executed automatically at the time of an event.
--------------------------------------------------------------------------------------------------------
Workbook Events:
The following images shows the various workbook events available.


Examples:
The following is an example for a workbook event 'Workbook_Open' , for this event I I wrote vba code that shows a Welcome message when workbook is open.
Private Sub Workbook_Open()
MsgBox "Hai Welcome To MS-Excel", vbInformation, "Welcome"
End Sub

The following is an example for a workbook event 'Workbook_BeforeClose' , for this event I I wrote vba code that shows a Thank You message before the workbook is close.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
MsgBox "Thank You for Using MS-Excel", vbInformation, "Thanks..See You Again"
End Sub


Note:
In this way you can define other events as you wish.
The scope of  events you  defined for a workbook are limited to that workbook only.
--------------------------------------------------------------------------------------------------------

WorkSheet Events:
The following images shows the various worksheet events available.



Examples:
The following is an example for a work sheet event 'Worksheet_SelectionChange' , for this event I I wrote vba code that shows a Active Cell Address message when when you change a selection in that particular sheet.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

MsgBox "You Have Selected " & ActiveCell.Address
End Sub

Note:
In this way you can define other events as you wish.
The scope of events you  defined for a worksheet are limited to that particular worksheet only.

Thanks, TAMATAM
       


Featured Post from this Blog

How to compare Current Snapshot Data with Previous Snapshot in Power BI

How to Dynamically compare two Snapshots Data in Power BI Scenario: Suppose, we have a sample Sales data, which is stored with Monthly Snaps...

Popular Posts from this Blog