101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy].pdf



Comments



Description

7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] HOME BLOG BASICS FUNCTIONS FORMULAS Useful Macro Codes Examples Search Macro codes can save you a ton of time. You can automate small as well as heavy tasks with VBA codes. Awesome And, do you know with the help of macros, you can break all the limitations of excel which you ✓ Formu SUMIFS w think excel has? Calculate Condition So, today, I have listed some of the useful codes to help you become more productive in your Count Un day to day work.  SUMPROD ✓ Charti You can use these macro codes even if you haven't used VBA before that. All you have to do Milestone just paste these useful macros codes in your VBA editor. Populatio Waffle Ch These codes will exactly do the same thing which headings are telling you. For your Thermom convenience, please follow these steps to add these codes to your workbook. Excel Piv ✓ VBA VBA To C First of all, make sure you have your developer tab on your excel ribbon. If you don't have ON-OFF B please use these simple steps to activate developer tab. VBA IF S Useful Ma » Go to your developer tab and click on "Visual Basic". 90% Dis 516 Shares = Share w Share Share m Pin » On the le side in "Project Window", right click on the name of your workbook and insert a new module. http://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 1/47 7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] » Just paste your codes into the module and close it. » Now, go to your developer tab and click on the macro button. » It will show you a window with a list of the macros you have in your le. » And, you can run a macro from that list. Don’t have time to read the entire list right now? No worries. Let me send you a Free E-Book so you can read it when it’s convenient for you. Just let me know where to send it. First Name 516 Shares Email = Share w Share Share Download Your Copy m Pin 101 Macro Codes Examples 1. create a backup of a current workbook 52. Closing Message 2. close all workbooks at once 53. convert date into day 3. hide all but the active worksheet 54. convert date into year 4. Unhide All Hidden Worksheets 55. remove time from date 5. Delete All but the Active Worksheet 56. remove date from date & time 6. Copy Active Worksheet Into a New 57. add header/footer date Workbook 58. custom header/footer 7. Protect All Worksheets Instantly 59. disable/enable get pivot data 8. Convert All Formulas Into Values 60. convert to upper case 9. Remove Spaces from Selected Cells 61. convert to lower case http://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 2/47 7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] 10. Highlight Duplicates from Selection 62. convert to proper case 11. Hide All Pivot Table Subtotals 63. convert to sentence case 12. Refresh All Pivot Tables 64. remove a character from selection 13. Resize All Charts in a Worksheet 65. relative to an absolute reference 14. Highlight the Active Row and Column 66. remove the apostrophe from a number 15. Save selected range as a PDF 67. highlight negative numbers 16. Create a Table of Content 68. highlight speci c text 17. Remove Characters from a string 69. remove decimals from numbers 18. Active Workbook in an Email 70. multiply all the values by a number 19. Convert Range into an image 71. add a number in all the numbers 20. Insert a Linked Picture 72. calculate the square root 21. Highlight Top 10 Values 73. calculate the cube root 22. Add Serial Numbers 74. highlight cells with comments 23. Insert Multiple Worksheets 75. highlight alternate rows in the selection - 24. Highlight Named Ranges 76. highlight cells with misspelled words 25. Highlight Greater than Values 77. protect all the cells with formulas 26. Highlight Lower than Values 78. add a-z alphabets in a range 27. Protect Worksheet 79. count open unsaved workbooks 28. Unprotect Worksheet 80. delete all blank worksheets 29. Convert Text To Upper Case 81. convert Roman numbers into Arabic number 30. Convert Text To Lower Case 82. use goal seek 31. Insert Multiple Columns 516 Shares = Share w Share 83. unhideShare all rowsm Pincolumns and 32. Insert Multiple Rows 84. save each worksheet as a single pdf 33. Auto Fit Columns 85. count/highlight cells with error in entire 34. Auto Fit Rows worksheet 35. Remove Text Wrap 86. count/highlight cells with a speci c in 36. Unmerge Cells entire worksheet 37. Change Chart Type 87. highlight all the cells in the worksheet 38. Paste Chart as an Image which are blank but have an invisible space 39. Add Chart Title 88. highlight max value in the range 40. Reverse Text 89. highlight min value in the range 41. Sort Worksheets 90. highlight unique values 42. Add Workbook to a mail Attachment 91. show progress on status bar 43. Activate R1C1 Reference Style 92. disable page breaks 44. Activate A1 Reference Style 93. highlight di erence in columns http://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 3/47 7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] 45. Open Calculator 94. highlight di erence in rows 46. Use Text To Speech 95. print comments 47. Activate User Form 96. print narrow margin 48. Insert TimeStamp 97. print selection 49. Create Pivot Table 98. print custom pages 50. Update Pivot Table Range 99. remove negative signs 51. Welcome Message 100. replace blank cells with zeros 101. Your Favorite One 1. create a backup of a current workbook This is one of the most useful macros which can help you to save a backup le of your current workbook. It will save a backup le in the same directory where your current le is saved. And, it will also add the current date with the name of the le. Sub FileBackUp() ThisWorkbook.SaveCopyAs Filename:=ThisWorkbook.Path & _ "" & Format(Date, "mm-dd-yy") & " " & _ ThisWorkbook.name End Sub 516 Shares = Share w Share Share m Pin 2. close all workbooks at once Use this macro code to close all open workbooks. This macro code will rst 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 http://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 4/47 Worksheets If ws.Visible = xlSheetVisible Next ws End Sub 516 Shares = Share w Share Share m Pin 5. hide all but the active worksheet Now.DisplayAlerts = False ws. if you want to un-hide all the worksheets which you have hide with previous code. Sub HideWorksheet() Dim ws As Worksheet For Each ws In ThisWorkbook. let's say if you want to hide all the worksheets in your workbook other than the active worksheet.name Then Application.Name <> ThisWorkbook.ActiveSheet. When you run this macro it will compare the name of the active worksheet with other worksheets and then delete them.com/blog/useful-macro-codes-for-vba-newcomers/ 5/47 . here is the code for that.Worksheets ws.DisplayAlerts = True End If http://excelchamps.Name Then ws. this macro is useful for you. Sub DeleteWorksheets() Dim ws As Worksheet For Each ws In ThisWorkbook.Visible = xlSheetHidden End If Next ws End Sub 4. This macro code will do this for you. unhide all hidden worksheets And.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] 3.name <> ThisWorkbook.Worksheets If ws.ActiveSheet. delete all but the active worksheet If you want to delete all the worksheets other than the active sheet.Delete Application. Sub UnhideAllWorksheet() Dim ws As Worksheet For Each ws In ActiveWorkbook. = Share w Share Share m Pin For Each ws In ActiveWorkbook. Sub ConvertToValues() Dim MyRange As Range Dim MyCell As Range Select Case MsgBox("You Can't Undo This Action.ActiveSheet. When you run this macro it will quickly change the formulas into absolute values. convert all formulas into values Simply convert formulas into values. just run this macro code and it will do the same for you.com/blog/useful-macro-codes-for-vba-newcomers/ 6/47 .Worksheets(1) End Sub 7. you will get an input box to enter a password. Sub ProtectAllWorskeets() Dim ws As Worksheet Dim ps As String 516 Shares vbOKCancel) ps = InputBox("Enter a Password. click OK.". vbYesNoCancel. When you run this macro.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Next ws End Sub 6. And.Copy _ Before:=Workbooks. make sure to take care about CAPS. http://excelchamps. Once you enter your password. protect all worksheets instantly If you want to protect your all worksheets in one go here is a code for you.Worksheets ws. " & "Save Workbook First?". copy active worksheet into a new workbook Let's say if you want to copy your active worksheet in a new workbook. Sub CopyWorksheetToNewWorkbook() ThisWorkbook. It's a super time saver.Protect Password:=ps Next ws End Sub 8.Add. Save Case Is = vbCancel 516 Shares = Share w Share Share m Pin 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. remove spaces from selected cells One of the most useful macros from this list.Formula = MyCell.Save Case Is = vbCancel Exit Sub End Select Set MyRange = Selection For Each MyCell In MyRange If MyCell.com/blog/useful-macro-codes-for-vba-newcomers/ 7/47 .7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] "Alert") Case Is = vbYes ThisWorkbook.HasFormula Then MyCell. " & "Save Workbook First?". "Alert") Case Is = vbYesThisWorkbook. _ vbYesNoCancel. http://excelchamps. It will check your selection and then remove extra spaces from that. You can also change the color from the code.Value End If Next MyCell End Sub 9. Sub RemoveSpaces() Dim myRange As Range Dim myCell As Range Select Case MsgBox("You Can't Undo This Action. if you want to hide all the subtotals.com/blog/useful-macro-codes-for-vba-newcomers/ 8/47 . Sub HideSubtotals() Dim pt As PivotTable Dim pf As PivotField On Error Resume Next Set pt = ActiveSheet.PivotTables(ActiveCell. refresh all pivot tables A super quick method to refresh pivot tables. make sure to select a cell from your pivot table and then run this macro. just run this code. 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 http://excelchamps.name) If pt Is Nothing Then MsgBox "You must place your cursor inside of a PivotTable.PivotTable.Value) > 1 Then myCell. myCell.Subtotals(1) = False Next pf End Sub 12." Exit Sub End If 516 Shares For Each pf In pt. First of all. hide all pivot table subtotals A er creating a pivot table.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Sub HighlightDuplicateValues() Dim myRange As Range Dim myCell As Range Set myRange = Selection For Each myCell In myRange If WorksheetFunction.PivotFields = Share w Share Share m Pin pf.ColorIndex = 36 End If Next myCell End Sub 11.CountIf(myRange.Interior.Subtotals(1) = True pf. Count With ActiveSheet.Width = 300 . http://excelchamps. by applying this macro you will not able to edit the cell by double click.Height = 200 End With Next i End Sub 516 Shares = Share Share Share Pin 14. » Close VBE & you are done.com/blog/useful-macro-codes-for-vba-newcomers/ 9/47 .ChartObjects.Worksheets For Each pt In ws.RefreshTable Next pt Next ws End Sub 13. Sub Resize_Charts() Dim i As Integer For i = 1 To ActiveSheet. Remember that.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Dim pt As PivotTable For Each ws In ThisWorkbook. 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. » Paste the code into it & Select the “BeforeDoubleClick” from event drop down menu. » Open VBE (ALT + F11). If hidden). resize all charts in a worksheet Make all chart same in size. Select your workbook & double click on the name of a particular worksheet in which you want to activate the macro.PivotTables pt. Here are the quick steps to apply this code. » Go to Project Explorer (Ctrl + R.ChartObjects(i) . highlight the active row wand column m I really love this macro code whenever I have to analyze a data table. Count With ActiveSheet .Name & "'!A1". _ ScreenTip:=Sheets(i).Address Range(strRange).EntireColumn. it's hard to navigate now. Sub SaveAsPDF() Selection.Cells. _ TextToDisplay:=Sheets(i).Cells(i.Select End Sub 15.Address & ".ExportAsFixedFormat Type:=xlTypePDF.Cells.EntireRow.Name = "Table of Content" For i = 1 To Sheets.DisplayAlerts = False Worksheets("Table of Content").Add Before:=ThisWorkbook. create a table of content Let's say you have more than 100 worksheets in your workbook.Worksheets(1) ActiveSheet.Address & ".7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range.Hyperlinks.Cells." & _ Target.Add _ Anchor:=ActiveSheet. save selected range as a PDF Select a range. When you run this code it will create a new worksheet and list the name of all worksheets with a hyperlink to them. Cancel As Boolean) Dim strRange As String strRange = Target. OpenAfterPublish:=True End Sub 16. Don't worry this macro code will rescue everything.DisplayAlerts = True On Error GoTo 0 ThisWorkbook. It's really cool. _ SubAddress:="'" & Sheets(i). 1). Sub TableofContent() Dim i As Long On Error Resume Next 516 Shares = Share w Share Share m Pin Application.Name." & _ Target. _ Address:="". run this macro and you will get a PDF le for that selected range.Name http://excelchamps. And.Sheets.com/blog/useful-macro-codes-for-vba-newcomers/ 10/47 .Delete Application. For example: If you want to remove rst characters from a cell. All you need is to refer to a cell or insert a text into the function and number of characters to remove from the text string. And if you want to send this mail directly.Body = "Hello Team. email.to = "Sales@FrontLinePaper. and body text in code.cnt) End Function 18.FullName . remove characters from a string Simply remove characters from the starting of a text string.com" . Public Function removeFirstC(rng As String.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] End With Next i End Sub 17.display End With Set OutMail = Nothing Set OutApp = Nothing End Sub 19. Sub Send_Mail() 516 Shares = Share w Share Share m Pin Dim OutApp As Object Dim OutMail As Object Set OutApp = CreateObject("Outlook. you need to enter 1 incnt. Please find attached Growth Report.CreateItem(0) With OutMail ." . You can change the subject. cnt As Long) removeFirstC = Right(rng.com/blog/useful-macro-codes-for-vba-newcomers/ 11/47 . active workbook in an email Use this macro code to quickly send your active workbook in an e-mail.Subject = "Growth Report" . convert range into an image http://excelchamps.Application") Set OutMail = OutApp.Send" instead of ". use ".Add ActiveWorkbook.  It has two arguments "rng" for the text string and "cnt" for the count of characters to remove.Display".Attachments. Len(rng) . Sub PasteAsPicture() Application. This VBA code will convert your selected range into a linked picture and you can use that image anywhere you want.FormatConditions.Pictures.Pictures. You just have to select the range and once you run this code it will automatically insert a picture for that range.FormatConditions(1). Sub LinkedPicture() Selection.com/blog/useful-macro-codes-for-vba-newcomers/ 12/47 .Color = -16752384 .FormatConditions(1) .AddTop10 Selection.FormatConditions. highlight top 10 values Instantly.SetFirstPriority With Selection.Copy ActiveSheet. 516 Shares = Share w Share Share m Pin Sub TopTen() Selection.Percent = False End With With Selection. convert range into an image Paste selected range as an image.Rank = 10 . insert a linked picture Insert a live image.PatternColorIndex = xlAutomatic .Interior .Paste(Link:=True).Paste.FormatConditions(1).Count). Just select a range and run this macro and it will highlight top 10 values with the green color.Select End Sub 21.Copy ActiveSheet.Color = 13561798 http://excelchamps.FormatConditions(Selection.Font .Select End Sub 20.CutCopyMode = False Selection.TopBottom = xlTop10Top .7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] 19.TintAndShade = 0 End With With Selection. highlight named ranges http://excelchamps.FormatConditions(1).". Count:=i End Sub 24.Add After:=ActiveSheet. it will instantly insert serial numbers starting from the active cell.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] . "Enter Serial Numbers") For i = 1 To i ActiveCell. Once you run this macro it will show an input box and you need enter last number for serial numbers A er that.Value = i ActiveCell. Sub InsertMultipleSheets() Dim i As Integer i = InputBox("Enter number of sheets to insert. "Enter Multiple Sheets") Sheets. Sub AddSerialNumbers() Dim i As Integer On Error GoTo Last i = InputBox("Enter Value". add serial numbers This macro code will help you to automatically add serial numbers in your excel sheet.Activate Next i Last: Exit Sub End Sub 23.TintAndShade = 0 End With Selection. insert multiple worksheets 516 Shares = Share w Share Share m Pin Insert multiple worksheets in a single shot.StopIfTrue = False End Sub 22. 0). When you run this macro code you will get an input box to enter the total number of sheets you want to enter. You can use this code if you want to add multiple worksheets in your workbook in a single shot.com/blog/useful-macro-codes-for-vba-newcomers/ 13/47 .Offset(1. "Enter Value") 516 Shares Selection.FormatConditions. 0.Interior. Sub HighlightRanges() Dim RangeName As Name Dim HighlightRange As Range On Error Resume Next For Each RangeName In ActiveWorkbook. 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. http://excelchamps.com/blog/useful-macro-codes-for-vba-newcomers/ 14/47 .Delete = Share w Share Share m Pin Selection. Sub HighlightGreaterThanValues() Dim i As Integer i = InputBox("Enter Greater Than Value". 218.Add Type:=xlCellValue. Once you run this code it will ask you for the value from which you want to highlight all lower values.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Instantly highlight named ranges.Names Set HighlightRange = RangeName. Formula1:=i Selection. 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 greater values.Color = RGB(31.RefersToRange HighlightRange.Interior.FormatConditions.Font. 154) End With End Sub 26.FormatConditions.Count).ColorIndex = 36 Next RangeName End Sub 25.FormatConditions(1) .SetFirstPriority With Selection. highlight greater than values Instantly highlight greater than values. 0) .FormatConditions(Selection. Operator:=xlGreater.Color = RGB(0. Sub UnprotectWS() ActiveSheet. All you have to do just mention your password in the code. "Enter Value") Selection. unprotect worksheet 516 with Unprotect your worksheet Sharesa single = Share click.Delete Selection.FormatConditions.Protect "mypassword". 0.Interior. protect worksheet Protect your worksheet with a single click. Sub ProtectWS() ActiveSheet. w Share Share m Pin If you want to unprotect your worksheet you can use this macro code. 79) End With End Sub 27. If you want to protect your worksheet you can use this macro code. 83. 0) . True.Color = RGB(0.Color = RGB(217.com/blog/useful-macro-codes-for-vba-newcomers/ 15/47 . This code will help you to convert your text into upper case text in a click.FormatConditions.SetFirstPriority With Selection.Font. convert text to upper case Convert selected text into upper case text.Count).Unprotect "mypassword" End Sub 29. All you have to do just mention your password which you have used while protecting your worksheet. True End Sub 28.FormatConditions.FormatConditions(1) .FormatConditions(Selection. Operator:=xlLower.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Sub HighlightLowerThanValues() Dim i As Integer i = InputBox("Enter Lower Than Value". Formula1:=i Selection.Add Type:=xlCellValue. http://excelchamps. Once you run this macro it will show an input box and you need to enter the number of 516 Shares columns you want to insert.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] 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.Select On Error GoTo Last i = InputBox("Enter number of columns to insert".EntireColumn.com/blog/useful-macro-codes-for-vba-newcomers/ 16/47 . = Share w Share Share m Pin Sub InsertMultipleColumns() Dim i As Integer Dim j As Integer ActiveCell. This code will help you to convert your text into lower case text in a click.Insert Shift:=xlToRight. 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. CopyOrigin:=xlFormatFromRightorAbove Next j Last: Exit Sub End Sub 32. "Insert Columns") For j = 1 To i Selection. insert multiple rows http://excelchamps. Sub AutoFitRows() Cells. Sub InsertMultipleRows() Dim i As Integer Dim j As Integer ActiveCell.Insert Shift:=xlToDown.EntireRow.Select Cells. insert multiple rows Quickly insert multiple rows. This macro code will select all the cells in your worksheet and instantly auto t all the row.AutoFit End Sub 34.Select http://excelchamps. "Insert Columns") For j = 1 To i Selection. Once you run this macro it will show an input box and you need to enter the number of rows you want to insert. auto t rows Quickly auto t all the row in your worksheet.com/blog/useful-macro-codes-for-vba-newcomers/ 17/47 .Select On Error GoTo Last i = InputBox("Enter number of columns to insert".EntireColumn. 516 Shares = Share w Share Share m Pin Sub AutoFitColumns() Cells.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] 32. CopyOrigin:=xlFormatFromRightorAbove Next j Last: Exit Sub End Sub 33. This macro code will select all the cells in your worksheet and instantly auto t all the columns. auto t columns Quickly auto t all the columns in your worksheet. you can nd all those types from here.WrapText = False Cells. This code will help you to remove text wrap from all the worksheet in a single click.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Cells.Select Selection. There are di erent codes for di erent types. All you have to do just specify to which type you want to convert. remove text wrap Remove text wrap from entire worksheet.com/blog/useful-macro-codes-for-vba-newcomers/ 18/47 .EntireRow.AutoFit Cells.EntireColumn. Sub RemoveWrapText() Cells.UnMerge End Sub 516 Shares = Share w Share Share m Pin 37. Sub ChangeChartType() ActiveChart. paste chart as an image http://excelchamps. It will rst select all the columns and then remove text wrap. Select your cells and run this code. Below code will convert selected chart to a clustered column chart.AutoFit End Sub 36. This code will help you to convert chart type without using chart options from the tab.AutoFit End Sub 35. It will unmerge all the cells from the selection. change chart type Convert a chart from one to another. Sub UnmergeCells() Selection. unmerge cells Unmerge all the cells.ChartType = xlColumnClustered End Sub 38.EntireRow. "Chart Title") On Error GoTo Last ActiveChart.com/blog/useful-macro-codes-for-vba-newcomers/ 19/47 .Text = i 516 Shares = Share w Share Share m Pin Last: Exit Sub End Sub 40.Select End Sub 39.Pictures.ChartTitle. This code will help you to convert your chart into an image. sort worksheets http://excelchamps.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] 38. Sub AddChartTitle() Dim i As Variant i = InputBox("Please enter your chart title". reverse text A simple custom function to reverse text. You will get an input box to enter chart title. Sub ConvertChartToPicture() ActiveChart.ChartArea. you need to select your chart and the run this code.strReverse(cell. You just need to select your chart and run this code. add chart title Add or change chart title. First of all. Public Function rvrse(ByVal cell As Range) As String rvrse = VBA.SetElement (msoElementChartTitleAboveChart) ActiveChart. 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.Range("A1").Copy ActiveSheet.Paste.Select ActiveSheet. paste chart as an image Create an image of your chart.Value) End Function 41. Name) > UCase$(Sheets(j + 1).Move After:=Sheets(j + 1) End If End If Next j Next i 516 Shares = Share w Share Share m Pin End Sub 42. _ vbYesNoCancel + vbQuestion + vbDefaultButton1.Show End Sub 43. 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". This code will help you to sort worksheets in your workbook according to their name. add workbook to a mail attachment Attach your excel le in a mail.Count .Move After:=Sheets(j + 1) End If ElseIf iAnswer = vbNo Then If UCase$(Sheets(j).Dialogs(xlDialogSendMail).com/blog/useful-macro-codes-for-vba-newcomers/ 20/47 .7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] 41.Name) Then Sheets(j). Sub OpenWorkbookAsAttachment() Application.1 If iAnswer = vbYes Then If UCase$(Sheets(j).Name) Then Sheets(j). Once you run this macro it will open your default mail client and attached active workbook with it as an attachment. sort worksheets Quickly sort worksheets.Name) < UCase$(Sheets(j + 1).Count For j = 1 To Sheets. activate r1c1 reference style http://excelchamps. "Sort Worksheets") For i = 1 To Sheets. ReferenceStyle = xlA1 Then Application.ReferenceStyle = xlR1C1 End If End Sub 44. use text to speech Make excel speak. This macro code will help you to activate A1 reference style without using excel options. Open Calculator Open windows calculator.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Activate R1C1 without using excel options. http://excelchamps.ReferenceStyle = xlA1 Else Application.ReferenceStyle = xlR1C1 Then Application.ActivateMicrosoftApp Index:=0 End Sub 46. Sub ActivateR1C1() If Application.ReferenceStyle = xlR1C1 Else Application.ReferenceStyle = xlA1 End If End Sub 516 Shares = Share w Share Share m Pin 45. Sub OpenCalculator() Application.com/blog/useful-macro-codes-for-vba-newcomers/ 21/47 . When you run this code it will open window calculator which you can use for your calculations. This macro code will help you to activate R1C1 reference style without using excel options. Activate A1 Reference Style Activate A1 without using excel options. Sub ActivateA1() If Application. excel will speak all the text what you have in that range.Select Next i End Sub 49. you can insert a time stamp from 00:00 to 23:00. With this code. cell by cell. insert timestamp Quickly insert the time stamp. There is a default user form in excel which you can use for data entry.Offset(RowOffset:=1.NumberFormat = "[$-409]h:mm AM/PM. ColumnOffset:=0). create a pivot table Automate your pivot table. http://excelchamps. you can use this code to activate that user form. activate user form User form without any VBA code. Sub Speak() Selection.FormulaR1C1 = i & ":00" ActiveCell.@" ActiveCell.ShowDataForm End Sub 48. Sub DataForm() ActiveSheet. And.Speak End Sub 47.com/blog/useful-macro-codes-for-vba-newcomers/ 22/47 . You can create a pivot table with this code in seconds with this code.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Just select a range and run this code. Sub TimeStamp() Dim i As Integer 516 Shares = Share w Share Share m Pin For i = 1 To 24 ActiveCell. Delete Sheets.Add Before:=ActiveSheet ActiveSheet.Cells(Rows.PivotCaches. TableName:="SalesPivotTable") 'Insert Row Fields With ActiveSheet.PivotFields("Year") . 2).Count.Column Set PRange = DSheet. 1). _ Share m Pin TableName:="SalesPivotTable") 'Insert Blank Pivot Table Set PTable = PCache.Position = 1 End With With ActiveSheet.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] 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.End(xlUp).Cells(2.Name = "PivotTable" Application.PivotTables("SalesPivotTable"). SourceData:=PRange).Orientation = xlRowField .PivotFields("Month") . LastCol) 'Define Pivot Cache Set PCache = ActiveWorkbook.Cells(1. 1).Count).Cells(1.CreatePivotTable _ (TableDestination:=PSheet.Cells(1.Position = 2 End With 'Insert Column Fields http://excelchamps. Columns.Row LastCol = DSheet. _ 516 Shares = Share w Share CreatePivotTable(TableDestination:=PSheet.com/blog/useful-macro-codes-for-vba-newcomers/ 23/47 .DisplayAlerts = True Set PSheet = Worksheets("PivotTable") Set DSheet = Worksheets("Data") 'Define Data Range LastRow = DSheet.Resize(LastRow. 1).PivotTables("SalesPivotTable").Orientation = xlRowField .DisplayAlerts = False Worksheets("PivotTable").Create _ (SourceType:=xlDatabase.End(xlToLeft). Range("A1") http://excelchamps.TableStyle2 = "PivotStyleMedium9" End Sub 50.NumberFormat = "#.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] With ActiveSheet.PivotTables("SalesPivotTable").Position = 1 .PivotFields("Amount") .PivotFields("Zone") .Worksheets("Pivot3") 'Enter in Pivot Table Name PivotName = "PivotTable2" 'Defining Staring Point & Dynamic Range Data_Sheet.com/blog/useful-macro-codes-for-vba-newcomers/ 24/47 .PivotTables("SalesPivotTable"). update pivot table range Automatically update pivot table range.Orientation = xlDataField .ShowTableStyleRowStripes = True ActiveSheet.Activate Set StartPoint = Data_Sheet.Orientation = xlColumnField .Name = "Revenue " End With 'Format Pivot Table ActiveSheet.Function = xlSum .PivotTables("SalesPivotTable").##0" . If you are not using Excel tables then you can use this code to update pivot table range.Position = 1 End With 'Insert Data Field With ActiveSheet.Worksheets("PivotTableData3") Set Pivot_Sheet = ThisWorkbook. Sub UpdatePivotTableRange() Dim Data_Sheet As Worksheet 516 Shares Dim Pivot_Sheet As Worksheet = Share w Share Share m Pin 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.PivotTables("SalesPivotTable"). " End Sub 51.End(xlToRight).Address(ReferenceStyle:=xlR1C1) 'Change Pivot Table Data Source Range Address Pivot_Sheet.Create(SourceType:=xlDatabase.com" End Sub 53.End(xlDown)." End Sub 52. All you have to do just name your macro "auto_open". Simply select the range of cells and run this macro. All you have to do just name your macro "close_open".7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] LastCol = StartPoint.PivotTables(PivotName). _ ChangePivotCache ActiveWorkbook.PivotTables(PivotName).Range(StartPoint.Name & "!" & DataRange.Column DownCell = StartPoint. welcome message You can use auto_open to perform a task on opening a le.Activate MsgBox "Your Pivot Table is now updated. Sub auto_open() MsgBox "Welcome To ExcelChamps & Thanks for downloading this file. LastCol)) NewRange = Data_Sheet.com/blog/useful-macro-codes-for-vba-newcomers/ 25/47 . Sub date2day() Dim tempCell As Range http://excelchamps. SourceData:=NewRange) 'Ensure Pivot Table is Refreshed Pivot_Sheet. convert date into day If you have dates in your worksheet and you want to convert all those dates into days then this code is for you. _ PivotCaches. closing message 516 Shares = Share w Share Share m Pin You can use close_open to perform a task on opening a le.Row Set DataRange = Data_Sheet. Cells(DownCell. Sub auto_close() MsgBox "Bye Bye! Don't forget to check other cool stuff on excelchamps.RefreshTable 'Complete Message Pivot_Sheet. Value = Day(tempCell) . convert date into year This code will convert dates into month years.Int(Rng. remove time from date If you have time with the date and you want to remove it then you can use this code.NumberFormat = "0" End With End If Next tempCell End Sub 54.Value = Year(tempCell) .NumberFormat = "0" End With End If 516 Shares = Share w Share Share m Pin Next tempCell End Sub 55.Value = VBA.Value For Each tempCell In Selection If IsDate(tempCell) = True Then With tempCell .Value = Selection.Value For Each tempCell In Selection If IsDate(tempCell) = True Then With tempCell .com/blog/useful-macro-codes-for-vba-newcomers/ 26/47 .Value) End If Next http://excelchamps. Sub removeTime() Dim Rng As Range For Each Rng In Selection If IsDate(Rng) = True Then Rng.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Selection. Sub date2year() Dim tempCell As Range Selection.Value = Selection. Sub removeDate() Dim Rng As Range For Each Rng In Selection If IsDate(Rng) = True Then Rng.Fix(Rng. enter custom value in the input box. remove date from date & time It will return only time from a date and time value.com/blog/useful-macro-codes-for-vba-newcomers/ 27/47 .PageSetup .VBA.LeftHeader = "" .RightFooter = "" End With ActiveWindow. To change the alignment of header or footer you can edit the code. Run this code.Value) End If NextSelection.Value .CenterHeader = "&D" 516 Shares = Share w Share Share m Pin . Sub dateInHeader() With ActiveSheet. custom header/footer And.RightHeader = "" . You can edit this code to simply switch into header and footer.CenterFooter = "" .LeftFooter = "" .7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Selection. add header/footer date Use this code to add a date into the header or footer in your worksheet.NumberFormat = "dd-mmm-yy" End Sub 56. http://excelchamps.View = xlNormalView End Sub 58. if you want to insert a custom header then this code is for you.NumberFormat = "hh:mm:ss am/pm" End Sub 57.Value = Rng. disable/enable get pivot data To disable/enable GetPivotData function you need to use Excel option. with this code you can do it in a single click.GenerateGetPivotData Share False w Share Share m Pin End Sub 60.PageSetup .Value = UCase(Rng) End If http://excelchamps.WorksheetFunction.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Sub customHeader() Dim myText As String myText = InputBox("Enter your text here".CenterFooter = "" . "Enter Text") With ActiveSheet.IsText(Rng) Then Rng.  Sub convertUpperCase() Dim Rng As Range For Each Rng In Selection If Application. Sub activateGetPivotData() Application.LeftFooter = "" . convert to upper case Select the cells and run this code.GenerateGetPivotData = True End Sub Sub deactivateGetPivotData() 516 Shares = = Application.RightFooter = "" End With End Sub 59. It will check each and every cell of selected range and then convert it into upper case text.CenterHeader = myText .RightHeader = "" . But.com/blog/useful-macro-codes-for-vba-newcomers/ 28/47 .LeftHeader = "" . And.IsText(Rng) Then Rng. convert to proper case And.com/blog/useful-macro-codes-for-vba-newcomers/ 29/47 .WorksheetFunction.Value= LCase(Rng) End If Next End Sub 62. this code will convert selected text into the proper case where you have the rst letter in capital and rest in small. 516 Shares Sub convertProperCase() = Share w Share Share m Pin Dim Rng As Range For Each Rng In Selection If WorksheetFunction. http://excelchamps.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Next End Sub 61. this code will help you convert normal text into sentence case.Proper(Rng. Just select a range of cells where you have text and run this code.Value) End If Next End Sub 63. Sub convertLowerCase() Dim Rng As Range For Each Rng In Selection If Application. you have the rst letter of the rst word in capital and rest all in words in small for a single sentence. convert to sentence case In text case.IsText(Rng) Then Rng. If a cell has a number or any value other than text that value will remain same.Value= WorksheetFunction. convert to lower case This code will help you to convert selected text into lower case text. HasFormula= True Then c. _ xlA1. remove a character from selection To remove a particular character from a selected cell you can use this code.Formula= Application. It will show you an input box to enter the character you want to remove. Replacement:="" Next End Sub 65.ConvertFormula(c.Formula. xlA1.Replace What:=rc.IsText(Rng) Then Rng.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Sub convertTextCase() Dim Rng As Range For Each Rng In Selection If WorksheetFunction.  Sub removeChar() Dim Rng As Range Dim rc As String rc = InputBox("Character(s) to Replace".Value= UCase(Left(Rng. Len(Rng) -1)) End If Next rng End Sub 64. xlAbsolute) End If Next c End Sub 66. "Enter Value") For Each Rng In Selection Selection. relative to an absolute 516 Shares = Share reference w Share Share m Pin If you want to convert reference of all the formula from relative to absolute then you can use this code. Sub relToAbs() For Each c In Selection If c. 1)) & LCase(Right(Rng. remove the apostrophe from a number http://excelchamps. Select the range of cells where you have formulas and run this macro.com/blog/useful-macro-codes-for-vba-newcomers/ 30/47 . com/blog/useful-macro-codes-for-vba-newcomers/ 31/47 . highlight negative numbers Select a range of cells and run this code. you can use this code.IsNumber(Rng) Then If Rng.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] If you have numeric data where you have an apostrophe before each number. It will check each cell from the range and highlight all cells the where you have a negative number.AddressLocal http://excelchamps.RangeSelection.Value End Sub 67.Count> 1 Then myTxt= ActiveWindow.RangeSelection. When you run it.Color= -16776961 End If End If Next End Sub 68.Font. highlight speci c text 516 Shares = Share w Share Share m Pin Suppose you have a large dataset and you want to check for a particular value. Sub highlightNegativeNumbers() Dim Rng As Range For Each Rng In Selection If WorksheetFunction.Value < 0 Then Rng. you will get an input box to enter the value to search for. For this.Value = Selection. Sub highlightValue() Dim myStr As String Dim myRg As Range Dim myTxt As String Dim myCell As Range Dim myChar As String Dim I As Long Dim J As Long On Error Resume Next If ActiveWindow. you run this code to remove it. Sub removeApostrophes() Selection. 7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Else myTxt= ActiveSheet.Count <> 2 Then MsgBox"the selected range can only contain two columns " GoTo LInput End If For I = 0 To myRg. . 0) .AddressLocal End If LInput: Set myRg= Application.Range("A1").Offset(I. .InputBox("please select the data range:".Characters(J.Count > 1 Then MsgBox"not support multiple columns" GoToLInput End If If myRg.UsedRange. 0).Text) Mid(.Value= Int(rng) rng.ColorIndex= 3 Next End With Next I End Sub 516 Shares = Share w Share Share m Pin 69.Areas. J.Offset(I. "Selection Required". myTxt.Value With myRg.NumberFormat= "0" Next rng End Sub http://excelchamps.Rows. remove decimals from numbers This code will simply help you to remove all the decimals from the numbers from the selected range.Count-1 myStr= myRg.Font. .ColorIndex= 1 For J = 1 To Len(. Len(myStr)). Sub removeDecimals() Dim lnumber As Double Dim lResult As Long Dim rng As Range For Each rng In Selection rng.Text.Range("B1"). 8) If myRg Is Nothing Then Exit Sub If myRg. Len(myStr)) = myStrThen .Font.com/blog/useful-macro-codes-for-vba-newcomers/ 32/47 .Columns. . It will rst ask you for the number with whom you want to multiple and then instantly multiply all the numbers with it.IsNumber(rng) Then rng. multiply all the values by a number Let’s you have a list of numbers and you want to multiply all the number with a particular.Value= rng+ i Else End If Nextrng End Sub 72.IsNumber(rng) Then rng. Select that range of cells and run this code. http://excelchamps. calculate the cube root To calculate cube root without applying a formula you can use this code.Value= Sqr(rng) Else End If Nextrng End Sub 73.Value = rng * c Else End If Next rng End Sub 71. add a number in all the numbers Just like multiplying you can also add a number into a set of numbers. 516 Shares = Share w Share Share m Pin "Input Required") For Each rngIn Selection If WorksheetFunction. Sub getSquareRoot() Dim rngAs Range Dimi As Integer For Each rngIn Selection If WorksheetFunction. Here’s the code. calculate the square root To calculate square root without applying a formula you can use this code.IsNumber(rng) Then rng. Sub addNumber() Dim rngAs Range DimiAs Integer i= InputBox("Enter number to multiple". Just useths code.com/blog/useful-macro-codes-for-vba-newcomers/ 33/47 . "Input Required") For Each rng In Selection If WorksheetFunction. Sub multiplyWithNumber() Dim rng As Range Dim c As Integer c = InputBox("Enter number to multiple".7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] 70. it will simply check all the selected cells and convert numbers to their square root. It will simply check all the selected cells and convert numbers to their square root. Sub highlightAlternateRows() Dim rng As Range For Each rng In Selection.Value = rng ^ (1 / 3) Else End If Nextrng End Sub 74.Style= "Note" End Sub 75.com/blog/useful-macro-codes-for-vba-newcomers/ 34/47 . Sub highlightCommentCells() Selection. highlight cells with comments To highlight all the cells with comments use this macro. highlight alternate rows in the selection By highlighting alternate rows you can make your data easily readable.RowMod 2 = 1 Then rng.IsNumber(rng) Then rng. And for this.Rows If rng. highlight cells with misspelled words http://excelchamps. 516 Shares = Share w Share Share m Pin It will simply highlight every alternate row in selected range.Value= rng^ (1 / 3) Else End If Next rng End Sub 76.Style= "20% -Accent1" rng.SpecialCells(xlCellTypeComments).Select Selection.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Sub getCubeRoot() Dim rng As Range Dimi As Integer For Each rng In Selection If WorksheetFunction. you can use below VBA code. Cells.Locked = False .Style= "Bad" End If Next rng End Sub 77.CheckSpelling(word:=rng.Text) Then rng. Sub HighlightMisspelledCells() Dim rng As Range For Each rng In ActiveSheet. Sub lockCellsWithFormulas() With ActiveSheet . It will check each cell from the selection and highlight the cell where is a misspelled word. highlight cells with misspelled words If you nd hard to check all the cells for spelling error then this code is for you. Beloware the code which you can use.Cells. 0). add a-z alphabets in a range Just like serial numbers you can also insert alphabets in your worksheet.Protect AllowDeletingRows:=True End With End Sub 516 Shares = Share w Share Share m Pin 78.com/blog/useful-macro-codes-for-vba-newcomers/ 35/47 . protect all the cells with formulas To protect cell with formula with a single click you can use this code.SpecialCells(xlCellTypeFormulas). Sub addcAlphabets() Dim i As Integer For i= 65 To 90 ActiveCell.Locked = True .7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] 76.Select Next i End Sub http://excelchamps.Offset(1.Unprotect .UsedRange If Not Application.Value= Chr(i) ActiveCell. Saved = False Then i = i + 1 End If Next book MsgBox i End Sub 516 Shares = Share w Share Share m Pin 80. delete if a worksheet is blank.ScreenUpdating= False Application. Sub VisibleWorkbooks() Dim book As Workbook Dim i As Integer For Each book In Workbooks If book.Select Next i End Sub 79. count open unsaved workbooks Let’s you have 5-10 open workbooks.DisplayAlerts= False For Each Ws In Application. 0). you can use this code to get the number of workbooks which are not saved yet.Value= Chr(i) ActiveCell. delete all blank worksheets Run this code and it will check all the worksheets in the active workbook. And.Delete End If Next http://excelchamps.WorksheetFunction.CountA(Ws.Offset(1.Worksheets If Application.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Sub addsAlphabets() Dim i As Integer For i= 97 To 122 ActiveCell.com/blog/useful-macro-codes-for-vba-newcomers/ 36/47 .UsedRange) = 0 Then Ws. Sub deleteBlankWorksheets() Dim Ws As Worksheet On Error Resume Next Application. Sub GoalSeekVBA() 516 Shares = Share w Share Share m Pin Dim Target As Long On Error GoTo Errorhandler Target = InputBox("Enter the required value".GoalSeek_ Goal:=Target.com/blog/useful-macro-codes-for-vba-newcomers/ 37/47 .Value For Each rng In Selection If Not WorksheetFunction. use goal seek Goal Seek can be super helpful for you to solve complex problems.ScreenUpdating= True Application. Sub convertToNumbers() Dim rng As Range Selection.Value= Selection. "Enter Value") Worksheets("Goal_Seek"). Learn more about goal seek from here before you use this code. _ ChangingCell:=Range("C2") End With Exit Sub Errorhandler: MsgBox("Sorry.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Application.IsNonText(rng) Then rng. value is not valid. This code will help you to convert Roman numbers into Arabic numbers.Activate With ActiveSheet .Value= WorksheetFunction. convert Roman numbers into Arabic number Sometimes it’s really hard to understand Roman numbers as serial numbers.DisplayAlerts= True End Sub 81.") End Sub 83. unhide all rows and columns http://excelchamps.Arabic(rng) End If Next rng End Sub 82.Range("C7") . Name & ".Hidden = False Rows. “ENTER-FOLDER-NAME-HERE" & ws. Sub UnhideRowsColumns() Columns.EntireRow.UsedRange If WorksheetFunction. this code will help you. count/highlight cells with a speci c in entire worksheet http://excelchamps. Sub SaveWorkshetAsPDF() Dimws As Worksheet For Each ws In Worksheetsws.ExportAsFixedFormat xlTypePDF.pdf" Nextws End Sub 85. save each worksheet as a single pdf This code will simply save all the worksheets in a separate PDF le.IsError(rng) Then i = i + 1 rng.com/blog/useful-macro-codes-for-vba-newcomers/ 38/47 .EntireColumn. You just need to change the folder name from the code.Style = "bad" End If Next rng MsgBox "There are total " & i & " error(s) in this worksheet. count/highlight cells with error in entire worksheet To highlight and count all the cells in which you have an error. Just run this code and it will return a message with the number error cells and highlight all the cells.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Instead of unhiding rows and columns on by one manually you can use this code to do this in a single go.Hidden = False End Sub 84. 516 Shares = Share w Share Share m Pin Sub highlightErrors() Dim rng As Range Dim i As Integer For Each rng In ActiveSheet." End Sub 86. it’s really hard to identify them. Sub highlightSpecificValues() Dim rng As Range Dim i As Integer Dim c As Variant c = InputBox("Enter Value To Highlight") For Each rng In ActiveSheet.Style = "Note" i = i + 1 End If Next rng MsgBox "There are total " & i &" "& c & " in this worksheet. highlight all the cells in the worksheet which are blank but have an invisible space Sometimes there are some cells which are blank but they have a single space.UsedRange If rng.Value = " " Then rng. This code will check all the cell in the worksheet and highlight all the cells which have a single space. And. Sub blankWithSpace() 516 Shares = Share w Share Share m Pin Dim rng As Range For Each rng In ActiveSheet.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] This code will help you to count the cells which have a speci c value which you will mention and a er that highlight all those cells. highlight max value in the range It will check all the selected cells and highlight the cell with the maximum value." End Sub 87.com/blog/useful-macro-codes-for-vba-newcomers/ 39/47 . Sub highlightMaxValue() Dim rng As Range http://excelchamps.UsedRange If rng = c Then rng. due to this.Style = "Note" End If Next rng End Sub 88. FormatConditions.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] For Each rng In Selection If rng = WorksheetFunction.com/blog/useful-macro-codes-for-vba-newcomers/ 40/47 . Sub highlightMinValue() Dim rng As Range For Each rng In Selection If rng = WorksheetFunction.Style = "Good" End If Next rng End Sub 89. highlight min value in the range It will check all the selected cells and highlight the cell with the Minimum value. http://excelchamps.DupeUnique = xlUnique uv.Delete Dim uv As UniqueValues Set uv = rng.Interior.Min(Selection) Then rng.Color = vbGreen End Sub 91.Style = "Good" End If Next rng End Sub 90.Max(Selection) Then rng.AddUniqueValues uv.FormatConditions. Sub highlightUniqueValues() 516 Shares = Share w Share Share m Pin Dim rng As Range Set rng = Selection rng. show progress on status bar By using this macro you can show the progress of a macro code on the status bar. This code will add serial numbers up to 5000 in your sheet and along with it will show progress on the status bar. highlight unique values This codes will highlight all the cells from the selection which has a unique value. ScreenUpdating= True End Sub 516 Shares = Share w Share Share m Pin 93.WorksheetsSht. 0) & "%" Next Application.Select Selection. Sub columnDifference() Range("H7:H8.DisplayPageBreaks= False Next Sht Next wb Application.ScreenUpdating= False For Each wbIn Application.ColumnDifferences(ActiveCell).StatusBar= " Please wait while printing the numbers " & Round((icntr/ 5000 * 100).7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Sub progressStatusBar() Application.Style= "Bad" End Sub 94. It will simply disable page breaks from all the open workbooks.com/blog/useful-macro-codes-for-vba-newcomers/ 41/47 . highlight difference in columns Using this code you can highlight the di erence between two columns (corresponding cells).Select Selection.StatusBar= "Start Printing the Numbers" For icntr= 1 To 5000 Cells(icntr. 1) = icntr Application.Workbooks For Each ShtIn wb. disable page breaks To disable page breaks use this code. Sub DisablePageBreaks() Dim wbAs Workbook Dim wksAs Worksheet Application. by using this code you can highlight di erence between two row (corresponding cells).StatusBar= "" End Sub 92.I7:I8"). highlight difference in rows And. http://excelchamps. 75) . IgnorePrintAreas:=False End Sub 97.SelectedSheets.25) .25) .InchesToPoints(0.Style= "Bad" End Sub 95. Just select a range and run this code.I7:I8").com/blog/useful-macro-codes-for-vba-newcomers/ 42/47 .InchesToPoints(0. You dont need to go to printing options and set printing range. print narrow margin Use this VBA code to take a print with a narrow margin.TopMargin= Application.Select Selection.75) . Collate:=True.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Sub rowDifference() Range("H7:H8.HeaderMargin= Application. When you run this macro it will automatically change margins to narrow.3) End With ActiveWindow. print selection This code will help you print selected range.InchesToPoints(0.BottomMargin= Application. Sub printComments() With ActiveSheet.3) .LeftMargin= Application .PrintOutCopies:=1.RightMargin= Application.Select Selection. Sub printNarrowMargin() With ActiveSheet.PageSetup 516 Shares = Share w Share Share m Pin .printComments= xlPrintSheetEnd End With End Sub 96.FooterMargin= Application. Let’s say you have 10 pages to print.RowDifferences(ActiveCell).PageSetup .InchesToPoints(0.InchesToPoints(0. print comments Use this macro to activate settings to print comments in the end of the page. http://excelchamps.InchesToPoints(0. a er using this code you will get all the comments on 11th last page. com/blog/useful-macro-codes-for-vba-newcomers/ 43/47 .Value= Abs(rng) End If http://excelchamps. "Enter Value") If Not WorksheetFunction. Let’s say you want to print pages from 5 to 10. Please try again. Collate:=True End Sub 516 Shares = Share w Share Share m Pin 99. Sub printCustomSelection() Dim startpageAs Integer Dim endpageAs Integer startpage= InputBox("Please Enter Start Page number.".".Value= Selection. Please try again.7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Sub printSelection() Selection.PrintOutCopies:=1. Just select a range and run this code.Value For Each rngIn Selection If WorksheetFunction.IsNumber(endpage) Then MsgBox"Invalid End Page number. Collate:=True End Sub 98. Sub removeNegativeSign() Dim rngAs Range Selection.IsNumber(startpage) Then MsgBox"Invalid Start Page number. remove negative signs This code will simply check all the cell in the selection and convert all the negative numbers into positive.". To:=endpage. You just need to run this VBA code and enter start page and end page. "Error" Exit Sub End If endpage= InputBox("Please Enter End Page number. "Error" Exit Sub End If Selection. Copies:=1. print custom pages Instead of using the setting from print options you can use this code to print custom page range. "Enter Value") If Not WorksheetFunction.".IsNumber(rng) Then rng.PrintOutFrom:=startpage. Sub replaceBlankWithZero() Dim rngAs Range Selection.Value For Each rngIn Selection If rng= "" Or rng= " " Then rng. you have help me to complete this list. It makes easier to use formula and use those cells in further calculations. please share with me in the comment section. Your Favorite One Now.Value= "0" Else End If Next rng End Sub 101. you can take your skills to whole next level.  30 Useful Excel Tips  80 Excel Keyboard Shortcuts  100 VBA Codes  100 Excel Functions http://excelchamps.Value= Selection. It will help you to win at your daily work using some smart tactics.com/blog/useful-macro-codes-for-vba-newcomers/ 44/47 .7/31/2017 101 Useful Macro Codes Examples For VBA Beginners + [Free PDF Copy] Next rng End Sub 100. If you have any useful macro code which you use in work to save your time. 516 Shares = Share w Share Share m Pin DOWNLOAD NOW EXCEL PRODUCTIVITY GUIDE With this guide. I would love to hear from you. you can add zeros in all those cells. replace blank cells with zeros For data where you have blank cells.
Copyright © 2024 DOKUMEN.SITE Inc.