Excel Productivity Guide

Get instant access to this free e-book fully loaded with Useful Excel Tips, 80+ Keyboard Shortcuts, and VBA Codes.

Useful Macro Codes For VBA Beginners

    useful macro codes

    Do you know with the help of these useful macros, you can break all the limitations of excel which you think excel has?

    You can use these macro codes even if you haven’t used VBA before that. All you have to do just paste these useful macros codes in your VBA editor.

    These codes will exactly do the same thing which headings are telling you. For your convenience, please follow these steps to add these codes to your workbook.

    First of all, make sure you have your developer tab on your excel ribbon. If you don’t have please use these simple steps to activate developer tab.

    • Go to your developer tab and click on “Visual Basic”.

    click on visual basic editor before you use these useful macros for excel

    • On the left side in “Project Window”, right click on the name of your workbook and insert a new module.

    add module to paste these useful macros for excel

    • Just paste your macro into the module and close it.
    • Now, go to your developer tab and use these codes from macros.

    Instant Access: Download this PDF Version to learn more about these useful macros.

    1. Create a Backup of a Current Workbook

    This is one of the most useful macros which can help you to save a backup file of your current workbook. It will create a backup file in the same directory where your current file is saved.

    And, it will also add the current date with the name of the file.

    Sub FileBackUp()
    ThisWorkbook.SaveCopyAs Filename:=ThisWorkbook.Path & _
    "\" & Format(Date, "mm-dd-yy") & " " & _
    ThisWorkbook.name
    End Sub

    2. Close All Workbooks at Once

    Use this macro code to close all open workbooks. This macro code will first check all the workbooks one by one and close them.

    If any of the worksheets is not saved, you’ll get a message to save it.

    Sub CloseAllWorkbooks()
    Dim wbs As Workbook
    For Each wbs In Workbooks
    wbs.Close SaveChanges:=True
    Next wb
    End Sub
    

    3. Hide All but the Active Worksheet

    Now, let’s say if you want to hide all the worksheets in your workbook other than the active worksheet. This macro code will do this for you.

    Sub HideWorksheet() 
    Dim ws As Worksheet 
    For Each ws In ThisWorkbook.Worksheets 
    If ws.Name <> ThisWorkbook.ActiveSheet.Name Then 
    ws.Visible = xlSheetHidden 
    End If 
    Next ws 
    End Sub

    4. Unhide All Hidden Worksheets

    And, if you want to un-hide all the worksheets which you hide with previous code, here is the code for that.

    Sub UnhideAllWorksheet()
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
    ws.Visible = xlSheetVisible
    Next ws
    End Sub

    5. Delete All but the Active Worksheet

    If you want to delete all the worksheets other than the active sheet, this macro is useful for you.

    When you run this macro it will compare the name of the active worksheet with other worksheets and then delete them.

    Sub DeleteWorksheets()
    Dim ws As Worksheet
    For Each ws In ThisWorkbook.Worksheets
    If ws.name <> ThisWorkbook.ActiveSheet.name Then
    Application.DisplayAlerts = False
    ws.Delete
    Application.DisplayAlerts = True
    End If
    Next ws
    End Sub

    learn excel vba course

    6. Copy Active Worksheet Into a New Workbook

    Let’s say if you want to copy your active worksheet in a new workbook, just run this macro code. And, it will do the same for you.

    It’s a super time saver.

    Sub CopyWorksheetToNewWorkbook()
    ThisWorkbook.ActiveSheet.Copy _
    Before:=Workbooks.Add.Worksheets(1)
    End Sub

    7. Protect All Worksheets Instantly

    Want to protect your all worksheets in one go?

    Here is a useful macro for you. When you run this macro, you will get an input box to enter a password. Once you enter your password, click OK. And, make sure to take care about CAPS.

    Sub ProtecAllWorskeets()
    Dim ws As Worksheet
    Dim ps As String
    ps = InputBox("Enter a Password.", vbOKCancel)
    For Each ws In ActiveWorkbook.Worksheets
    ws.Protect Password:=ps
    Next ws
    End Sub

    8. Convert All Formulas Into Values

    Simply convert formulas into values.

    When you run this macro it will quickly change the formulas into absolute values.

    Sub ConvertToValues()
    Dim MyRange As Range
    Dim MyCell As Range
    Select Case MsgBox("You Can't Undo This Action. " & "Save Workbook First?", vbYesNoCancel, "Alert")
    Case Is = vbYes
    ThisWorkbook.Save
    Case Is = vbCancel
    Exit Sub
    End Select
    Set MyRange = Selection
    For Each MyCell In MyRange
    If MyCell.HasFormula Then
    MyCell.Formula = MyCell.Value
    End If
    Next MyCell
    End Sub

    9. Remove Spaces from Selected Cells

    One of the most useful macros from this list.

    It will check your selection and then remove extra spaces from that.

    Sub RemoveSpaces()
    Dim myRange As Range
    Dim myCell As Range
    Select Case MsgBox("You Can't Undo This Action. " & "Save Workbook First?", _
    vbYesNoCancel, "Alert")
    Case Is = vbYes
    ThisWorkbook.Save
    Case Is = vbCancel
    Exit Sub
    End Select
    Set myRange = Selection
    For Each myCell In myRange
    If Not IsEmpty(myCell) Then
    myCell = Trim(myCell)
    End If
    Next myCell
    End Sub

    10. Highlight Duplicates from Selection

    This macro will check each cell of your selection and highlight the duplicate values . You can also change the color from the code.

    Sub HighlightDuplicateValues()
    Dim myRange As Range
    Dim myCell As Range
    Set myRange = Selection
    For Each myCell In myRange
    If WorksheetFunction.CountIf(myRange, myCell.Value) > 1 Then
    myCell.Interior.ColorIndex = 36
    End If
    Next myCell
    End Sub

    11. Hide All Pivot Table Subtotals

    After creating a pivot table, if you want to hide all the subtotals, just run this code.  First of all, make sure to select a cell from your pivot table and then run this macro.

    Sub HideSubtotals()
    Dim pt As PivotTable
    Dim pf As PivotField
    On Error Resume Next
    Set pt = ActiveSheet.PivotTables(ActiveCell.PivotTable.name)
    If pt Is Nothing Then
    MsgBox "You must place your cursor inside of a PivotTable."
    Exit Sub
    End If
    For Each pf In pt.PivotFields
    pf.Subtotals(1) = True
    pf.Subtotals(1) = False
    Next pf
    End Sub

    12. Refresh All Pivot Tables

    A super quick method to refresh pivot tables.

    Just run this code and all of your pivot tables in your workbook will be refresh in a single shot.

    Sub RefreshAllPivotTables()
    Dim ws As Worksheet
    Dim pt As PivotTable
    For Each ws In ThisWorkbook.Worksheets
    For Each pt In ws.PivotTables
    pt.RefreshTable
    Next pt
    Next ws
    End Sub

    13. Resize All Charts in a Worksheet

    Make all chart same in size.

    This macro code will help you to make all the charts of the same size. You can change the height and width of charts by changing it in macro code.

    Sub Resize_Charts()
    Dim i As Integer
    For i = 1 To ActiveSheet.ChartObjects.Count
    With ActiveSheet.ChartObjects(i)
    .Width = 300
    .Height = 200
    End With
    Next i
    End Sub

    14. Highlight the Active Row and Column

    I really love this macro code whenever I have to analyze a data table.

    Here are the quick steps to apply this code.

    • Open VBE (ALT + F11).
    • Go to Project Explorer (Ctrl + R, If hidden). Select your workbook & double click on the name of a particular worksheet in which you want to activate the macro.
    • Paste the code into it  & Select the “BeforeDoubleClick” from event drop down menu.
    • Close VBE & you are done.

    Remember that, by applying this macro you will not able to edit the cell by double click.

    Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    Dim strRange As String
    strRange = Target.Cells.Address & "," & _
    Target.Cells.EntireColumn.Address & "," & _
    Target.Cells.EntireRow.Address
    Range(strRange).Select
    End Sub

    15. Save selected range as a PDF

    Select the range, run this macro and you will get a PDF file for that selected range. It’s really cool.

    Sub SaveAsPDF()
    Selection.ExportAsFixedFormat Type:=xlTypePDF, OpenAfterPublish:=True
    End Sub

    16. Create a Table of Content

    Let’s say you have more than 100 worksheets in your workbook. And, it’s hard to navigate now.

    Don’t worry this macro code will rescue everything. When you run this code it will create a new worksheet and list the name of all worksheets with a  hyperlink to them.

    Sub TableofContent()
    Dim i As Long
    On Error Resume Next
    Application.DisplayAlerts = False
    Worksheets("Table of Content").Delete
    Application.DisplayAlerts = True
    On Error GoTo 0
    ThisWorkbook.Sheets.Add Before:=ThisWorkbook.Worksheets(1)
    ActiveSheet.Name = "Table of Content"
    For i = 1 To Sheets.Count
    With ActiveSheet
    .Hyperlinks.Add _
    Anchor:=ActiveSheet.Cells(i, 1), _
    Address:="", _
    SubAddress:="'" & Sheets(i).Name & "'!A1", _
    ScreenTip:=Sheets(i).Name, _
    TextToDisplay:=Sheets(i).Name
    End With
    Next i
    End Sub

    17. Remove Characters from a string

    Simply remove characters from the starting of a text string.

    All you need is to refer to a cell or insert a text into the function nad number of characters to remove from the text string.

    It has two arguments “rng” for the text string and “cnt” for the count of characters to remove. For example: If you want to remove first characters from a cell, you need to enter 1 in cnt.

    Public Function removeFirstC(rng As String, cnt As Long)
    removeFirstC = Right(rng, Len(rng) - cnt)
    End Function

    18. Active Workbook in an Email

    Use this macro code to quickly send your active workbook in an e-mail.

    You can change the subject, email, and body text in code. And if you want to send this mail directly, use “.Send” instead of “.Display”.

    Sub Send_Mail()
    Dim OutApp As Object
    Dim OutMail As Object
    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)
    With OutMail
    .to = "Sales@FrontLinePaper.com"
    .Subject = "Growth Report"
    .Body = "Hello Team, Please find attached Growth Report."
    .Attachments.Add ActiveWorkbook.FullName
    .display
    End With
    Set OutMail = Nothing
    Set OutApp = Nothing
    End Sub

    19. Convert Range into an image

    Paste selected range as an image. You just have to select the range and once you run this code it will automatically insert a picture for that range.

    Sub PasteAsPicture()
     Application.CutCopyMode = False
     Selection.Copy
     ActiveSheet.Pictures.Paste.Select
    End Sub

    20. Insert a Linked Picture

    Insert a live image. This VBA code will convert your selected range into a linked picture and you can use that image anywhere you want.

    Sub LinkedPicture()
    Selection.Copy
    ActiveSheet.Pictures.Paste(Link:=True).Select
    End Sub

    21. Highlight Top 10 Values

    Instantly. Just select a range and run this macro and it will highlight top 10 values with the green color.

    Sub TopTen()
    Selection.FormatConditions.AddTop10
     Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
     With SelectionWithFormatConditions(1)
     .TopBottom = xlTop10Top
     .Rank = 10
     .Percent = False
     End With
     With Selection.FormatConditions(1).Font
     .Color = -16752384
     .TintAndShade = 0
     End With
     With Selection.FormatConditions(1).Interior
     .PatternColorIndex = xlAutomatic
     .Color = 13561798
     .TintAndShade = 0
     End With
     Selection.FormatConditions(1).StopIfTrue = False
    End Sub

    22. Add Serial Numbers

    This macro code will help you to automatically add serial numbers in your excel sheet. Once you run this macro it will show an input box and you need enter last number for serial numbers

    After that, it will instantly insert serial numbers starting from the active cell.

    Sub AddSerialNumbers()
    Dim i As Integer
    On Error GoTo Last
    i = InputBox("Enter Value", "Enter Serial Numbers")
    For i = 1 To i 
     ActiveCell.Value = i
     ActiveCell.Offset(1, 0).Activate
     Next i
     Last:
     Exit Sub
    End Sub

    23. Insert Multiple Worksheets

    Insert multiple worksheets in a single shot.

    You can use this code if you want to add multiple worksheets in your workbook in a single shot. When you run this macro code you will get an input box to enter the total number of sheets you want to enter.

    Sub InsertMultipleSheets()
     Dim i As Integer
     i = InputBox("Enter number of sheets to insert.", "Enter Multiple Sheets")
     Sheets.Add After:=ActiveSheet, Count:=i
    End Sub

    24. Highlight Named Ranges

    Instantly highlight named ranges.

    If you are not sure about how many named ranges you have in your worksheet then you can use this code to highlight all of them.

    Sub HighlightRanges()
     Dim RangeName As Name
     Dim HighlightRange As Range
     On Error Resume Next
     For Each RangeName In ActiveWorkbook.Names
     Set HighlightRange = RangeName.RefersToRange
     HighlightRange.Interior.ColorIndex = 36
     Next RangeName
    End Sub

    learn excel vba course

    25. Highlight Greater than Values

    Instantly highlight greater than values.

    Once you run this code it will ask you for the value from which you want to highlight all greater values.

    Sub HighlightGreaterThanValues()
    Dim i As Integer
    i = InputBox("Enter Greater Than Value", "Enter Value")
    Selection.FormatConditions.Delete
     Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, Formula1:=i
     Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
     With Selection.FormatConditions(1)
     .Font.Color = RGB(0, 0, 0)
     .Interior.Color = RGB(31, 218, 154)
     End With
    End Sub

    26. Highlight Lower than Values

    Instantly highlight lower than values.

    Once you run this code it will ask you for the value from which you want to highlight all lower values.

    Sub HighlightLowerThanValues()
    
    Dim i As Integer
    i = InputBox("Enter Lower Than Value", "Enter Value")
    Selection.FormatConditions.Delete
     Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlLower, Formula1:=i
     Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
     With Selection.FormatConditions(1)
     .Font.Color = RGB(0, 0, 0)
     .Interior.Color = RGB(217, 83, 79)
     End With
    End Sub
    

    27. Protect Worksheet

    Protect your worksheet with a single click.

    If you want to protect your worksheet you can use this macro code. All you have to do just mention your password in the code.

    Sub ProtectWS()
    ActiveSheet.Protect "mypassword", True, True
    End Sub

    28. Unprotect Worksheet

    Unprotect your worksheet with a single click.

    If you want to unprotect your worksheet you can use this macro code. All you have to do just mention your password which you have used while protecting your worksheet.

    Sub UnprotectWS()
    ActiveSheet.Unprotect "mypassword"
    End Sub
    

    29. Convert Text To Upper Case

    Convert selected text into upper case text.

    This code will help you to convert your text into upper case text in a click.

    Sub ConvertUpperCase()
    
    Dim rng As Range
    
    For Each rng In Selection
     rng = UCase(rng)
     Next rng
    
    End Sub

    30. Convert Text To Lower Case

    Convert selected text into lower case text.

    This code will help you to convert your text into lower case text in a click.

    Sub ConvertLowerCase()
    
    Dim rng As Range
    
    For Each rng In Selection
     rng = LCase(rng)
     Next rng
    
    End Sub

    31. Insert Multiple Columns

    Quickly insert multiple columns.

    Once you run this macro it will show an input box and you need to enter the number of columns you want to insert.

    Sub InsertMultipleColumns()
    
    Dim i As Integer
    Dim j As Integer
    
    ActiveCell.EntireColumn.Select
    
    On Error GoTo Last
    
    i = InputBox("Enter number of columns to insert", "Insert Columns")
    
    For j = 1 To i
     
     Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromRightorAbove
     
     Next j
     
    Last:
    
    Exit Sub
    
    End Sub

    32. Insert Multiple Rows

    Quickly insert multiple rows.

    Once you run this macro it will show an input box and you need to enter the number of rows you want to insert.

    Sub InsertMultipleRows()
    
    Dim i As Integer
    Dim j As Integer
    
    ActiveCell.EntireRow.Select
    
    On Error GoTo Last
    
    i = InputBox("Enter number of columns to insert", "Insert Columns")
    
     For j = 1 To i
     
     Selection.Insert Shift:=xlToDown, CopyOrigin:=xlFormatFromRightorAbove
     
     Next j
     
    Last:
    
    Exit Sub
    
    End Sub

    33. Auto Fit Columns

    Quickly auto fit all the columns in your worksheet.

    This macro code will select all the cells in your worksheet and instantly autofit all the columns.

    Sub AutoFitColumns() 
    
    Cells.Select 
    
    Cells.EntireColumn.AutoFit 
    
    End Sub

    34. Auto Fit Rows

    Quickly auto fit all the row in your worksheet.

    This macro code will select all the cells in your worksheet and instantly autofit all the row.

    Sub AutoFitRows() 
    Cells.Select 
    Cells.EntireRow.AutoFit 
    End Sub

    35. Remove Text Wrap

    Remove text wrap from entire worksheet.

    This code will help you to remove text wrap from all the worksheet in a single click. It will first select all the columns and then remove text wrap.

    Sub RemoveWrapText() 
    Cells.Select Selection.WrapText = False 
    Cells.EntireRow.AutoFit 
    Cells.EntireColumn.AutoFit 
    End Sub

    36. Unmerge Cells

    Unmerge all the cells.

    Select your cells and run this code. It will unmerge all the cells from the selection.

    Sub UnmergeCells() 
    Selection.UnMerge 
    End Sub

    37. Change Chart Type

    Convert a chart from one to another.

    This code will help you to convert chart type without using chart options from the tab. All you have to do just specify to which type you want to convert.

    Below code will convert selected chart to a clustered column chart. There are different codes for different types, you can find all those types from here.

    Sub ChangeChartType() 
    ActiveChart.ChartType = xlColumnClustered 
    End Sub

    38. Paste Chart as an Image

    Create an image of your chart. 

    This code will help you to convert your chart into an image. You just need to select your chart and run this code.

    Sub ConvertChartToPicture()
     ActiveChart.ChartArea.Copy
     ActiveSheet.Range("A1").Select
     ActiveSheet.Pictures.Paste.Select
    End Sub

    39. Add Chart Title

    Add or change chart title.

    First of all, you need to select your chart and the run this code. You will get an input box to enter chart title.

    Sub AddChartTitle()
    Dim i As Variant
    i = InputBox("Please enter your chart title", "Chart Title")
    On Error GoTo Last
    ActiveChart.SetElement (msoElementChartTitleAboveChart)
    ActiveChart.ChartTitle.Text = i
    Last:
    Exit Sub
    End Sub

    40. Reverse Text

    A simple custom function to reverse text.

    All you have to do just enter “rvrse” function in a cell and refer to the cell in which you have text which you want to reverse.

    Public Function rvrse(ByVal cell As Range) As String
     rvrse = VBA.strReverse(cell.Value)
    End Function

    41. Sort Worksheets

    Quickly sort worksheets.

    This code will help you to sort worksheets in your workbook according to their name.

    Sub SortWorksheets()
    Dim i As Integer
    Dim j As Integer
    Dim iAnswer As VbMsgBoxResult
    
    iAnswer = MsgBox("Sort Sheets in Ascending Order?" & Chr(10) _
     & "Clicking No will sort in Descending Order", _
     vbYesNoCancel + vbQuestion + vbDefaultButton1, "Sort Worksheets")
     For i = 1 To Sheets.Count
     For j = 1 To Sheets.Count - 1
    
    If iAnswer = vbYes Then
     If UCase$(Sheets(j).Name) > UCase$(Sheets(j + 1).Name) Then
     Sheets(j).Move After:=Sheets(j + 1)
     End If
    
    ElseIf iAnswer = vbNo Then
     If UCase$(Sheets(j).Name) < UCase$(Sheets(j + 1).Name) Then
     Sheets(j).Move After:=Sheets(j + 1)
    
    End If
     End If
    
    Next j
     Next i
    
    End Sub

    42. Add Workbook to a mail Attachment

    Attach your excel file in a mail.

    Once you run this macro it will open your default mail client and attached active workbook with it as an attachment.

    Sub OpenWorkbookAsAttachment()
    Application.Dialogs(xlDialogSendMail).Show
    End Sub

    43. Activate R1C1 Reference Style

    Activate R1C1 without using excel options.

    This macro code will help you to activate R1C1 reference style without using excel options.

    Sub ActivateR1C1()
     If Application.ReferenceStyle = xlA1 Then
     Application.ReferenceStyle = xlR1C1
     Else
     Application.ReferenceStyle = xlR1C1
     End If
    End Sub

    44. Activate A1 Reference Style

    Activate A1 without using excel options.

    This macro code will help you to activate A1 reference style without using excel options.

    Sub ActivateA1()
    If Application.ReferenceStyle = xlR1C1 Then
     Application.ReferenceStyle = xlA1
    Else
     Application.ReferenceStyle = xlA1
    End If
    End Sub

    45. Open Calculator

    Open windows calculator.

    When you run this code it will open window calculator which you can use for your calculations.

    Sub OpenCalculator()
     Application.ActivateMicrosoftApp Index:=0
    End Sub

    46. Use Text To Speech

    Make excel speak.

    Just select a range and run this code, excel will speak all the text what you have in that range, cell by cell.

    Sub Speak()
    Selection.Speak
    End Sub

    47. Activate User Form

    User form without any VBA code.

    There is a default user form in excel which you can use for data entry. And, you can use this code to activate that user form.

    Sub DataForm()
     ActiveSheet.ShowDataForm
    End Sub

    48. Insert TimeStamp

    Quickly insert the time stamp.

    With this code, you can insert a time stamp from 00:00 to 23:00.

    Sub TimeStamp()
     Dim i As Integer
     For i = 1 To 24
     ActiveCell.FormulaR1C1 = i & ":00"
     ActiveCell.NumberFormat = "[$-409]h:mm AM/PM;@"
     ActiveCell.Offset(RowOffset:=1, ColumnOffset:=0).Select
     Next i
    End Sub

    49. Create Pivot Table

    Automate your pivot table.

    You can create a pivot table with this code in seconds with this code.

    Sub InsertPivotTable()
    
    'Declare Variables
    Dim PSheet As Worksheet
    Dim DSheet As Worksheet
    Dim PCache As PivotCache
    Dim PTable As PivotTable
    Dim PRange As Range
    Dim LastRow As Long
    Dim LastCol As Long
    
    'Delete Preivous Pivot Table Worksheet & Insert a New Blank Worksheet With Same Name
    On Error Resume Next
    Application.DisplayAlerts = False
    Worksheets("PivotTable").Delete
    Sheets.Add Before:=ActiveSheet
    ActiveSheet.Name = "PivotTable"
    Application.DisplayAlerts = True
    Set PSheet = Worksheets("PivotTable")
    Set DSheet = Worksheets("Data")
    
    'Define Data Range
    LastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
    LastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
    Set PRange = DSheet.Cells(1, 1).Resize(LastRow, LastCol)
    
    'Define Pivot Cache
    Set PCache = ActiveWorkbook.PivotCaches.Create _
    (SourceType:=xlDatabase, SourceData:=PRange). _
    CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), _
    TableName:="SalesPivotTable")
    
    'Insert Blank Pivot Table
    Set PTable = PCache.CreatePivotTable _
    (TableDestination:=PSheet.Cells(1, 1), TableName:="SalesPivotTable")
    
    'Insert Row Fields
    With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("Year")
            .Orientation = xlRowField
            .Position = 1
    End With
    With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("Month")
            .Orientation = xlRowField
            .Position = 2
    End With
    
    'Insert Column Fields
    With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("Zone")
            .Orientation = xlColumnField
            .Position = 1
    End With
    'Insert Data Field
    With ActiveSheet.PivotTables("SalesPivotTable").PivotFields("Amount")
            .Orientation = xlDataField
            .Position = 1
            .Function = xlSum
            .NumberFormat = "#,##0"
            .Name = "Revenue "
    End With
    'Format Pivot Table
    ActiveSheet.PivotTables("SalesPivotTable").ShowTableStyleRowStripes = True
    ActiveSheet.PivotTables("SalesPivotTable").TableStyle2 = "PivotStyleMedium9"
    End Sub

    50. Update Pivot Table Range

    Automatically update pivot table range.

    If you are not using Excel tables then you can use this code to update pivot table range.

    Sub UpdatePivotTableRange()
     
    Dim Data_Sheet As Worksheet
    Dim Pivot_Sheet As Worksheet
    Dim StartPoint As Range
    Dim DataRange As Range
    Dim PivotName As String
    Dim NewRange As String
    Dim LastCol As Long
    Dim lastRow As Long
     
    'Set Pivot Table & Source Worksheet
    Set Data_Sheet = ThisWorkbook.Worksheets("PivotTableData3")
    Set Pivot_Sheet = ThisWorkbook.Worksheets("Pivot3")
     
    'Enter in Pivot Table Name
    PivotName = "PivotTable2"
     
    'Defining Staring Point & Dynamic Range
    Data_Sheet.Activate
    Set StartPoint = Data_Sheet.Range("A1")
    LastCol = StartPoint.End(xlToRight).Column
    DownCell = StartPoint.End(xlDown).Row
    Set DataRange = Data_Sheet.Range(StartPoint, Cells(DownCell, LastCol))
     
    NewRange = Data_Sheet.Name & "!" & DataRange.Address(ReferenceStyle:=xlR1C1)
     
    'Change Pivot Table Data Source Range Address
    Pivot_Sheet.PivotTables(PivotName). _
    ChangePivotCache ActiveWorkbook. _
    PivotCaches.Create(SourceType:=xlDatabase, SourceData:=NewRange)
     
    'Ensure Pivot Table is Refreshed
    Pivot_Sheet.PivotTables(PivotName).RefreshTable
     
    'Complete Message
    Pivot_Sheet.Activate
    MsgBox "Your Pivot Table is now updated."
    End Sub

    51. Welcome Message

    Show a message while opening a file.

    You can use auto_open to perform a task on opening a file. All you have to do just name your macro “auto_open”.

    Sub auto_open()
    MsgBox "Welcome To ExcelChamps & Thanks for downloading this file."
    End Sub

    52. Closing Message

    Show a message while closing a file.

    You can use close_open to perform a task on opening a file. All you have to do just name your macro “close_open”.

    Sub auto_close()
    MsgBox "Bye Bye! Don't forget to check other cool stuff on excelchamps.com"
    End Sub
    

    Conclusion

    As I said, you can break all the barriers with VBA. But the important point is you need to use it for the right tasks, at the right time.

    I am sure above codes will help you to automate your daily work and you will be able to save a lot of time.

    In the end, I want to ask you something, if you have any code which helps you to make your life easier, please share with in the comment box.

    I would love to hear from you.


    learn excel vba course