Wednesday, October 22, 2014

How to use VLOOKUP and HLOOKUP ?

VlookUp stands for vertical column look up. This formula is used to find the value in the column vertically.

e.g.


We have a table of employee details, where employee id, first name, last name, email id and contact number data is there. The data is in column A, B, C, D and E respectively.


This table contains data for 10000 employees.


Problem : We need to get the email id and contact number data for 43 employees in the output. 

The only input we have is employee id in column H.










Solution - Vlookup


below is the formula which can be used to get the employee details -


Get email id

=VLOOKUP(H2,A:E,4,0)

how it works ?

1. here H2 is the reference employee id for which we need to find the data
2. A:E is the table range where our data is present
3. 4 is the number of the column starting from column A, in which our data is present
4. 0 is for exact match

Similarly use the below formula to  get contact number

=VLOOKUP(H2,A:E,5,0)

Note - 

1. The reference value which we are using to look up the data should be always in the left hand side of the required output data. in above example employee id is on the left side of the data.
2. The data range should start from the reference number column. In above example range is starting from (A;E) where A is employee id column.
3. The number for the output column should be counted from the start column of reference value. In example above we are counting the output value from column A, i.e. our output values are in column 4 and 5.



 
HlookUp stands for horizontal row look up. This formula is used to find the value in the rows horizontally.

e.g.


We have a table of students marks details, where column headers are 

Student Name
English
Maths
Science
History.

The data is in column A, B, C, D and E respectively.


Data under Student Name column is -

Amol

Vijay

Kiran

Vidya

....
...
..
. and more

This table contains data for 5000 Students.

Problem : We need to find the marks of English and Science, only for Vijay and Vidya or for list of say, 30 students only.

The input we have is the table data in which we can use the user name and the subject name to lookup the required value.


example table:



Solution : Hlookup

below is the formula which can be used to get the required output
=HLOOKUP(B8,$A$1:$E$5,3,0)

result = 32

Below is the screenshot of output table, this table is on cells A8:C10.


how it works ?

1. here B8 is the subject name (English) for which we need to find the data
2. $A$1:$E$5 is the table range where our input data is present
3. 3 is the number of the row starting from column header, in which our data is present
4. 0 is for exact match


Similarly use the below formula to  get data for subject Science
=HLOOKUP(C8,$A$1:$E$5,3,0)

result = 27


There is one challenge in the above formula for which we need to take help of one more formula combining with Hlookup.



Challenge : For 5000 students how to enter the number automatically in step 3 above

Solution : use the MATCH formula to find the row number in which our required data is present

e.g. find row number for Vijay, use the below match formula

=MATCH(A9,$A$1:$A$5)


result = 3



how it works ?

1. here A9 is the Student name (Vijay) for which we need to find the data
2. $A$1:$A$5 is the table range where our input data is present


Now combining the Match formula with Hlookup, we can get the required output without manual entry.

Our actual Hlookup formula:
=HLOOKUP(B8,$A$1:$E$5,3,0)

Formula combined with MATCH:

=HLOOKUP(B8,$A$1:$E$5,MATCH(A9,$A$1:$A$5),0)

result = 32



How to calculate days in a month using Excel formula ?


Below is the formula which can be used to calculate the days in a specific month.


Enter any date in cell B2


Copy paste the below formula in Cell B3


=DAY(DATE(YEAR(B2),MONTH(B2)+1,1)-1)



e.g. if the value in the Cell B2 is 10/22/2014 (i.e. 22nd october 2014)


Then the result in the cell B3 will be 31



How it works ?


we will break up the above formula in  parts.


1. Year(B2)          - this will provide us the year of the date result (2014) 

2. Month(2) + 1   - this will provide us the next months number result (11)
3. 1                     - one is entered to get 1st date of next month 
4. -1                     - this minus one will give us last day of previous month result (10/31/2014)
5. Day                 - this formula will provide us the required day output result (31)

conclusion - Initially we are finding first day of next month, then subtracting it with 1 to get last day of current month and at the end with the help of day formula we get the last day i.e. 31 as output.


Done...

Monday, June 30, 2014

How to use the CASE and the INPUTBOX in Excel VBA ?

Below is the example of the input box and the Case, used in excel VBA to check, the letter belongs to which grade description.

Copy paste the below code to any of the Excel VBA module and run it. you will get the pop-up window to enter the input letter. Enter the letter and click OK.


You will get the message box with the letter is for description value.


Sub testcase()


Dim grade As String

grade = "A"
grade = InputBox("Enter the Grade from A to D")
Select Case grade

Case "A"

MsgBox grade & " is for High Distinction"

Case "B"

MsgBox grade & " is for Credit"

Case "C"

MsgBox grade & " is for Pass"

Case Else

MsgBox grade & " is for Fail"

End Select

End Sub

Using the code examples in the above macro, this can be modified to do different tasks at different situations.

e.g., if you want to write the grade against the marks in excel, we can modify the above code adding the loop code and mapping the grades to marks.

Done...

Thursday, May 15, 2014

How to find character in text using excel formula ?

You can use below formula to find the character in any word.

e.g. cell B1 contains the text Marks with 50% and we need to find if it contains %, we can write the below formula - 

=MID(B1,FIND("%",B1,1),1)

Output of the above formula will be %.



You can further customize this formula to write Found -

=IF(MID(B1,FIND("%",B1,1),1)="%","Found")

Output of the above formula will be Found.



If there is no "%" in cell B1 the formula will return #value! error, to overcome this we can customize the formula as below -

=IFERROR(IF(MID(B1,FIND("%",B1,1),1)="%","Found"),"Not Found")

If the character is missing in cell B1 then the output of the above formula will be Not Found.



You can replace the % to any character you need to find and you will get the output accordingly.


Done....

Tuesday, May 6, 2014

Find the difference between the two dates in excel

Below is the inbuilt function in excel which will retrieve the difference between two dates. We can get the results in number of days, number of months or number of years.

We can take a simple example to find the age difference from date of birth till today -


Date of Birth    - 23/01/1984    (enter value in cell A1)

Today's Date   - 06/05/2014    (enter value in cell B1)

=DATEDIF(L2,M2,"Y")&" Years, "&DATEDIF(L2,M2,"YM")&" Months, and "&DATEDIF(L2,M2,"MD")&" Days"


The output of the above formula will be -

30 Years, 4 Months, and 13 Days



=DateDif(A1,B1,"Y") = output will be number of years (Y)

=DateDif(A1,B1,"M") = output will be number of months (M)
=DateDif(A1,B1,"D") = output will be number of days (D)
=DateDif(A1,B1,"YM") = output will be number of calendar months from start year, here the months will be for current year
=DateDif(A1,B1,"YD") = output will be number of calendar days from start year, here the days will be for current year
=DateDif(A1,B1,"MD") = output will be number of calendar days from start month, here the days will be for current month


Above combination of codes can be used at different situations, one example we saw above -

1. To find the Age
2. Remaining days to your wedding
3. Days remaining to Expiring warranty or maintenance
4. Total employment experience
5. Property Agreement going to expire
...... and more

Done....


*all codes in this blog are tested on Excel 2010

Friday, April 4, 2014

Find first and last date of any month

You can find the first date of any month in three different conditions mentioned below:

First Day of any month - 


Enter Month and Year in "cell D4" e.g. December-2014 and use the below formula in "cell E4" to get the first date of the month


=DATE(YEAR(D4),MONTH(D4),1)



Enter any date value in "cell D5" e.g. 4-Apr-2014 and use the below formula 

in "cell E5" to get the first date of the month

=DATE(YEAR(D5),MONTH(D5),1)



Enter any Month name in "cell D6" e.g. February and use the below formula 

in "cell E6" to get the first date of the month

=(D6&"/1")+0



Enter any Year in "cell D7" e.g. 2014 and use the below formula 

in "cell E7" to get the first date of the month

=DATE(D7,1,1)



Below is the screenshot for the above formulas :










Last Day of month - 

Below formula is used to get the last date of any month, based on the selected date

=DATE(YEAR(B3),MONTH(B3)+1,0)

here for e.g., if we say B3 = 5/6/2014, then output of above formula will be 5/31/2014



Last Day of Previous month - 

Below formula is used to get the last date of previous month, based on the selected date

=DATE(YEAR(B3),MONTH(B3),0)


here for e.g., if we say B3 = 5/6/2014, then output of above formula will be 4/30/2014


These formulas can be used in different conditions where formula based data analysis is required and the data keeps changing based on different dates.

e.g. Case :

You can find the first date and keep adding that date by 1 to get the next dates of the month.

Done......

Wednesday, March 26, 2014

12 good to know tips in Excel VBA

1. Copy file from one location to other using Excel VBA code

You can use this code to copy paste the file from one destination to other

e.g. if you require to take backups of the file on daily basis.

Sub Copy_File()
' Declare variables
    Dim filename As String, Source As String, Destination As String

'Set values
    filename = "abc"
    Source = "C:\Test\Desert.jpg"
    Destination = "C:\Test\Backup\" & filename & ".jpg"

'File copy code
    FileCopy Source, Destination
    
End Sub



2. Copy and Save file with Date Time Stamp using Excel VBA

You can use below code to copy and save the file with the date and time stamp. This code is same as one of the Copy file code in my previous blog, Just check the changes in the code for Destination.

Sub Copy_File_dt ()

' Declare variables
    Dim filename As String, Source As String, Destination As String

'Set values
    filename = "abc_"
    Source = "C:\Test\Desert.jpg"
    Destination = "C:\Test\Backup\" & filename & Format(Now(), "mm_dd_yyyy hh mm AMPM") & ".jpg"

'File copy code
    FileCopy Source, Destination
    
End Sub


3. Remove hyperlinks from Excel, using VBA code

There is a simple one line code to do this. Copy paste below VBA code in excel VBA window and run. All hyperlinks from the active sheet will be removed.

Sub removeallhyperlinks()

ActiveSheet.Hyperlinks.Delete

End Sub



you can also use below code:

Sub removeallhyperlinks()

Cells.Hyperlinks.Delete

End Sub



4. Resize all charts to same size using Excel VBA

Below code is used to re-size all the charts to same size from the the active sheet. Copy paste below code in your excel VBA window and run the macro to resize the charts. 

Sub ResizeCharts()

' assigning the chart as chartobject, which will identify the charts in the activesheet
Dim chart As ChartObject

For Each chart In ActiveSheet.ChartObjects

        With chart.Parent

' change the numbers in the below brackets (5) to change the size of the chart. Here we are using inches to set the chart size.        
        chart.Height = Application.InchesToPoints(5)
        chart.Width = Application.InchesToPoints(10)
        
    End With

Next

MsgBox "All charts in the active sheet are resized !"

End Sub


In above code we are using inches as the measure to change the chart size. Similarly we can use centimeters to re-size the charts.

Sub ResizeCharts()

' assigning the chart as chartobject, which will identify the charts in the activesheet
Dim chart As ChartObject

For Each chart In ActiveSheet.ChartObjects

        With chart.Parent

' change the numbers in the below brackets (5) to change the size of the chart. Here we are using inches to set the chart size.        
        chart.Height = Application.CentimetersToPoints(5)
        chart.Width = Application.CentimetersToPoints(10)
        
    End With

Next

MsgBox "All charts in the active sheet are resized !"

End Sub


If you observe in the above code only two lines are changed.

   chart.Height = Application.CentimetersToPoints(5)
   chart.Width = Application.CentimetersToPoints(10)


5. How to deactivate Alerts while running macro in Excel VBA

You can deactivate the alerts received while running the VBA macro in excel, using below code -

Application.DisplayAlerts = False

You can also deactivate the screen updating while running the macro by using the below code -

Application.ScreenUpdating = False

If your macro is moving from different tabs of worksheet or excel files, the screen will show the details of the macro's step. To disable this we can use the above code.

Below is one of the example, on how this codes can be used -

Sub deactivateAlerts()

Application.DisplayAlerts = False
Application.ScreenUpdating = False

Sheets("Sheet1").Select
ActiveSheet.Hyperlinks.Delete

Sheets("Sheet2").Select
ActiveSheet.Hyperlinks.Delete

Sheets("Sheet3").Select
ActiveSheet.Hyperlinks.Delete

Sheets("Sheet4").Select
ActiveSheet.Hyperlinks.Delete

Application.DisplayAlerts = True
Application.ScreenUpdating = True

MsgBox "Your macro is completed !"

End Sub


The simple code above used, to delete all the hyperlinks in 4 different sheets from your workbook. When the macro is running without the displayalerts = false and screenupdating = false, it will show the steps of macro on screen. 

When the displayalerts = false and screenupdating = false is used, you will see the same screen where you are running the macro and you will directly receive the message box stating "Your macro is completed !"

Don't forget to add the below lines before End Sub of your code.

Application.DisplayAlerts = True
Application.ScreenUpdating = True

These lines will reset the Alerts and Screen updating.


6. How to Open, Save As and Replace file using Excel VBA macro

Below is the macro which is used to Open, Save As and Replace the abc.xls file saved on location - C:\Users\Public\Documents\abc.xls


Sub ReplaceRename()

' Disable alerts
Application.DisplayAlerts = False

'Open file
Workbooks.Open filename:= _
      "C:\Users\Public\Documents\abc.xls"

'Save As and replace or Rename file. In below case we are saving the .xls file in .xlsx format. In case you need to rename the file, just change the abc.xlsx to newname.xlsx in below code
ActiveWorkbook.SaveAs filename:= _
       "C:\Users\Public\Documents\abc.xlsx", FileFormat:= _
        xlOpenXMLWorkbook, CreateBackup:=False

'Close workbook
ActiveWindow.Close

'Reset alerts
Application.DisplayAlerts = True

'Message pop-up
Msgbox "Macro completed successfully !"

'Exit Macro
End Sub


If we run the macro with the removing the display alerts code on line 2 of code, then we will receive below pop-up message. With the above code we will receive only below message - 

"Macro completed successfully !"



Above code is used only in case you are using excel file and need to convert the format from .xls to .xlsx or any other excel formats.

To replace or rename any other file format you can use the below code -

Sub RepRenanyfile()


'FileCopy Source, Destination
FileCopy "C:\Users\Public\Documents\abc.xls", "C:\Users\Public\Documents\def.xlsx"

MsgBox "Macro completed successfully !"

End Sub


7. How to create a function in excel to get the logged in USER Name

Below is the simple function which is used to get the logged in user name

Function GetUserName()
    GetUserName = Environ("UserName")
End Function


Once the above function is created in the module, you can write a formula in any cell in excel cell to get the output as logged in user's name -
=GetUserName()

Same macro can be used to give a popup message with the User name, with Msgbox code addition -

Function GetUserName()
    GetUserName = Environ("UserName")
    MsgBox "Logged in User Name is " & GetUserName
End Function


8. How to execute excel VBA macro on change of specific cell in excel sheet ?

Please follow the below steps to execute the task -

1. We need to go to Excel VBA editor by pressing ALT + F11
2. Double click on sheet which contains our target cell e.g. Sheet1
3. Add the below code to the sheet

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$E$3" Then
Call Macro1
End If
End Sub

4. If any value in cell E3 of Sheet1 is updated or changed the Macro1 will be executed
5. Insert new module and Add the below code to with name Macro1 

Sub Macro1()
MsgBox "The value entered in Range E3 is " & Range("E3").Value
End Sub

6. Now try changing the value in cell E3 of Sheet1, the Macro1 will be executed and you will get a messagebox pop-up window


9. How to select next column or row using excel VBA ?

Below are the codes using which you can move the active selection of cell to the Left, Right, Up or Down.

The code is -
Activecell.Offset(0,0)

The (0,0) in brackets represent the row and column.

Copy and paste the below code in your excel VBA window to test the working of the Offset code.


Sub TestOffset()

' Here the cursor on active sheet moves to next row (moves once), no change in column
ActiveCell.Offset(1, 0).Select 

' Here the cursor on active sheet moves to next column (moves once), no change in row
ActiveCell.Offset(0, 1).Select

' Here the cursor on active sheet moves to next row and next column
ActiveCell.Offset(1, 1).Select

' Here the cursor on active sheet moves to upper row (moves once), no change in column
ActiveCell.Offset(-1, 0).Select

' Here the cursor on active sheet moves to previous column (moves once), no change in row
ActiveCell.Offset(0, -1).Select

' Here the cursor on active sheet moves to upper row and previous column
ActiveCell.Offset(-1, -1).Select

'Using the above codes, you can select the columns or rows you need from activecell. Below are some examples -
ActiveCell.Offset(2, 0).Select
ActiveCell.Offset(-1, 2).Select
ActiveCell.Offset(2, 3).Select

End Sub



10. How to Resize and Reset the Comments in Excel using VBA code ?

Below code can be used to reset all comments to default location and size.

Copy paste the below code to any of the Excel VBA module and run it on the active sheet from which you need to reset the comments.

Sub resetcomments()
On Error Resume Next
Application.ScreenUpdating = False
Set allCommentsr = Range("A1").SpecialCells(xlCellTypeComments)

If
allCommentsr Is Nothing Then MsgBox "No comments in " & ActiveSheet.Name: GoTo Out

For Each
r In allCommentsr
With r.Comment
.Shape.Height = 55   'you can change the number you need to resize
.Shape.Width = 96    'you can change the number you need to resize
End With

r.Comment.Visible = True
r.Comment.Shape.Select True

With Selection
.Interior.ColorIndex = 19   'you can change the colorindex number for using different color
.Font.Bold = False            'you can change to True if you need the text in BOLD
.Font.Size = 8                  'you can change the number for font size you need
End With

r.Comment.Visible = False
Next r

Out:
Set allCommentsr = Nothing

MsgBox "All comments are resized and restored to default", vbInformation

Application.ScreenUpdating = True
End Sub


11. Add Start and End row to run the macro, in Excel VBA

Below code can be used to enter the start and end rows to run the macro for specific code. In the below example we have used the Msgbox code to display, the value in the specific cell when the macro is executed.

Sub testrow()
    
    Do While True
        line1 = InputBox("ENTER FIRST ROW NUMBER ")
        line1 = LTrim(RTrim(line1))
        If line1 <> " " Then
            Exit Do
         End If
    Loop

    Do While True
        line2 = InputBox("ENTER THE LAST ROW NUMBER ")
        line2 = LTrim(RTrim(line2))
        If line2 <> " " And line2 > 1 Then
            Exit Do
         End If
    Loop

    For irow = line1 To line2
    icol = 1
    
    a = Cells(irow, icol).Value
    
    MsgBox a ' You can change this line to call your macro or update any other code

    Next
    MsgBox "completed"
End Sub


12. How to filter the unwanted fields using Auto filter in Excel VBA ?

In below example, there are name of Subjects in column D. Say, we need to delete all rows except Hindi and Marathi subject using excel VBA code.

We can use the below code to execute the deletion task using VBA code. 

Sub Keep_HM()

'Deselect the subjects Hindi and Marathi
ActiveSheet.range("D:D").AutoFilter Field:=1, Criteria1:="<>HINDI", _
Operator:=xlAnd, Criteria2:="<>MARATHI"

'Delete the filtered cells
ActiveSheet.range("D1").CurrentRegion.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete

'Remove the filter from active sheet
ActiveSheet.AutoFilterMode = False

'Message box pop-up after execution
Msgbox "All subjects except, HINDI and MARATHI are deleted", vbInformation

End Sub




*all codes in this blog are tested on Excel 2010