Top 100 Useful Excel MACRO CODES Examples [VBA Library] + PDF
Có thể bạn quan tâm
Macro codes can save you a ton of time. You can automate small as well as heavy tasks with VBA codes.
And do you know? With the help of macros, you can break all the limitations of Excel which you think Excel has.
And today, I have listed some of the useful codes examples to help you become more productive in your day to day work.
You can use these codes even if you haven’t used VBA before that. But here’s the first thing to know:
What is a Macro Code?
In Excel, macro code is a programming code which is written in VBA (Visual Basic for Applications) language. The idea behind using a macro code is to automate an action which you perform manually in Excel, otherwise.
For example, you can use a code to print only a particular range of cells just with a single click instead of selecting the range > File Tab > Print > Print Select > OK Button.
How to use a Macro Code in Excel?
Before you use these codes, make sure you have your developer tab on your Excel ribbon to access VB editor. Once you activate developer tab you can use below steps to paste a VBA code into VB editor.
- Go to your developer tab and click on “Visual Basic” to open the Visual Basic Editor.
- On the left side in “Project Window”, right click on the name of your workbook and insert a new module.
- Just paste your code 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 file from where you can run a macro from that list.
Learn VBA in 1 Hour
(List) 100+ Macro Examples (CODES) for VBA Beginners
- This is my Ultimate VBA Library, which I update on a monthly basis with new codes. Don’t forget to check the VBA Examples Sectionꜜ at the end of this list.
- VBA is one of the Advanced Excel Skills.
- To manage all of these codes, make sure to read about the Personal Macro Workbook so that you can use them in all the workbooks.
- I have tested all of these codes in different versions of Excel (2007, 2010, 2013, 2016, and 2019). If you find any errors in these codes, please share them with me.
Download the PDF File
Basic Codes
1. Add Serial Numbers
This macro code will automatically add serial numbers to your Excel sheet, which can be helpful if you work with large amounts of data.
Sub AddSerialNumbers()Dim i As IntegerOn Error GoTo Lasti = InputBox("Enter Value", "Enter Serial Numbers")For i = 1 To iActiveCell.Value = iActiveCell.Offset(1, 0).ActivateNext iLast:Exit SubEnd SubTo use this code, you need to select the cell from where you want to start the serial numbers and when you run this it shows you a message box where you need to enter the highest number for the serial numbers and click OK.
And once you click OK, it simply runs a loop and add a list of serial numbers to the cells downward.
2. Insert Multiple Columns
This code helps you to enter multiple columns in a single click.
Sub InsertMultipleColumns()Dim i As IntegerDim j As IntegerActiveCell.EntireColumn.SelectOn Error GoTo Lasti = InputBox("Enter number of columns to insert", "Insert Columns")For j = 1 To iSelection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromRightorAboveNext jLast: Exit SubEnd SubWhen you run this code, it asks you the number columns you want to add and when you click OK, it adds entered number of columns after the selected cell. If you want to add columns before the selected cell, replace the xlToRight to xlToLeft in the code.
3. Insert Multiple Rows
With this code, you can enter multiple rows in the worksheet. When you run this code, you can enter the number of rows to insert and make sure to select the cell from where you want to insert the new rows.
Sub InsertMultipleRows()Dim i As IntegerDim j As IntegerActiveCell.EntireRow.SelectOn Error GoTo Lasti = InputBox("Enter number of columns to insert", "Insert Columns")For j = 1 To iSelection.Insert Shift:=xlToDown, CopyOrigin:=xlFormatFromRightorAboveNext jLast: Exit SubEnd SubIf you want to add rows before the selected cell, replace the xlToDown to xlToUp in the code.
4. Auto Fit Columns
This code quickly auto fits all the columns in your worksheet.
Sub AutoFitColumns()Cells.SelectCells.EntireColumn.AutoFitEnd SubWhen you run this code, it will select all the cells in your worksheet and instantly auto-fit all the columns.
5. Auto Fit Rows
You can use this code to auto fit all the rows in a worksheet.
Sub AutoFitRows()Cells.SelectCells.EntireRow.AutoFitEnd SubWhen you run this code, it will select all the cells in your worksheet and instantly auto fit all the rows.
6. Remove Text Wrap
This code will help you to remove text wrap from the entire worksheet with a single click.
Sub RemoveTextWrap()Range("A1").WrapText = FalseEnd SubIt will first select all the columns and then remove text wrap and auto fit all the rows and columns. There’s also a shortcut that you can use (Alt + H +W) for but if you add this code to Quick Access Toolbar it’s convenient than a keyboard shortcut.
7. Unmerge Cells
This code simply uses the unmerge options which you have on the HOME tab.
Sub UnmergeCells()Selection.UnMergeEnd SubThe benefit of using this code is you can add it to the QAT and unmerge all the cell in the selection. And if you want to un-merge a specific range you can define that range in the code by replacing the word selection.
8. Open Calculator
In Windows, there is a specific calculator and by using this macro code you can open that calculator directly from Excel.
Sub OpenCalculator()Application.ActivateMicrosoftApp Index:=0End SubAs I mentioned that it’s for windows and if you run this code in the MAC version of VBA you’ll get an error.
This macro adds a date to the header when you run it. It simply uses the tag “&D” for adding the date.
Sub DateInHeader()With ActiveSheet.PageSetup.LeftHeader = "".CenterHeader = "&D".RightHeader = "".LeftFooter = "".CenterFooter = "".RightFooter = ""End WithEnd SubYou can also change it to the footer or change the side by replacing the “” with the date tag. And if you want to add a specific date instead of the current date you can replace the “&D” tag with that date from the code.
When you run this code, it shows an input box that asks you to enter the text which you want to add as a header, and once you enter it click OK.
Sub CustomHeader()Dim myText As StringmyText = InputBox("Enter your text here", "Enter Text")With ActiveSheet.PageSetup.LeftHeader = "".CenterHeader = myText.RightHeader = "".LeftFooter = "".CenterFooter = "".RightFooter = ""End WithEnd SubIf you see this closely you have six different lines of code to choose the place for the header or footer. Let’s say if you want to add left-footer instead of center header simply replace the “myText” to that line of the code by replacing the “” from there.
Formatting Codes
These VBA codes will help you to format cells and ranges using some specific criteria and conditions.
11. 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 RangeDim myCell As RangeSet myRange = SelectionFor Each myCell In myRangeIf WorksheetFunction.CountIf(myRange, myCell.Value) > 1 ThenmyCell.Interior.ColorIndex = 36End IfNext myCellEnd Sub12. Highlight the Active Row and Column
I really love to use this macro code whenever I have to analyze a data table.
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)Dim strRange As StringstrRange = Target.Cells.Address & "," & _Target.Cells.EntireColumn.Address & "," & _Target.Cells.EntireRow.AddressRange(strRange).SelectEnd SubHere 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 and select the “BeforeDoubleClick” from event drop down menu.
- Close VBE and you are done.
Remember that, by applying this macro you will not able to edit the cell by double click.
13. Highlight Top 10 Values
Just select a range and run this macro and it will highlight top 10 values with the green color.
Sub TopTen()Selection.FormatConditions.AddTop10Selection.FormatConditions(Selection.FormatConditions.Count).StFirstPriorityWith Selection.FormatConditions(1).TopBottom = xlTop10Top.Rank = 10.Percent = FalseEnd WithWith Selection.FormatConditions(1).Font.Color = -16752384.TintAndShade = 0End WithWith Selection.FormatConditions(1).Interior.PatternColorIndex = xlAutomatic.Color = 13561798.TintAndShade = 0End WithSelection.FormatConditions(1).StopIfTrue = FalseEnd Sub14. 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 NameDim HighlightRange As RangeOn Error Resume NextFor Each RangeName In ActiveWorkbook.NamesSet HighlightRange = RangeName.RefersToRangeHighlightRange.Interior.ColorIndex = 36Next RangeNameEnd Sub15. 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 Integeri = InputBox("Enter Greater Than Value", "Enter Value")Selection.FormatConditions.DeleteSelection.FormatConditions.Add Type:=xlCellValue, _Operator:=xlGreater, Formula1:=iSelection.FormatConditions(Selection.FormatConditions.Count).StFirstPriorityWith Selection.FormatConditions(1).Font.Color = RGB(0, 0, 0).Interior.Color = RGB(31, 218, 154)End WithEnd Sub16. 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 Integeri = InputBox("Enter Lower Than Value", "Enter Value")Selection.FormatConditions.DeleteSelection.FormatConditions.Add _Type:=xlCellValue, _Operator:=xlLower, _Formula1:=iSelection.FormatConditions(Selection.FormatConditions.Count).StFirstPriorityWith Selection.FormatConditions(1).Font.Color = RGB(0, 0, 0).Interior.Color = RGB(217, 83, 79)End WithEnd Sub17. Highlight Negative Numbers
Select a range of cells and run this code. It will check each cell from the range and highlight all cells where you have a negative number.
Sub highlightNegativeNumbers()Dim Rng As RangeFor Each Rng In SelectionIf WorksheetFunction.IsNumber(Rng) ThenIf Rng.Value < 0 ThenRng.Font.Color= -16776961End IfEnd IfNextEnd Sub18. Highlight Specific Text
Suppose you have a large data set, and you want to check for a particular value. For this, you can use this code. When you run it, you will get an input box to enter the value to search for.
Sub highlightValue()Dim myStr As StringDim myRg As rangeDim myTxt As StringDim myCell As rangeDim myChar As StringDim I As LongDim J As LongOn Error Resume NextIf ActiveWindow.RangeSelection.Count > 1 ThenmyTxt = ActiveWindow.RangeSelection.AddressLocalElsemyTxt = ActiveSheet.UsedRange.AddressLocalEnd IfLInput: Set myRg = _Application.InputBox _("please select the data range:", "Selection Required", myTxt, , , , , 8)If myRg Is Nothing ThenExit SubIf myRg.Areas.Count > 1 ThenMsgBox "not support multiple columns"GoTo LInputEnd IfIf myRg.Columns.Count <> 2 ThenMsgBox "the selected range can only contain two columns "GoTo LInputEnd IfFor I = 0 To myRg.Rows.Count - 1myStr = myRg.range("B1").Offset(I, 0).ValueWith myRg.range("A1").Offset(I, 0).Font.ColorIndex = 1For J = 1 To Len(.Text)Mid(.Text, J, Len(myStr)) = myStrThen.Characters(J, Len(myStr)).Font.ColorIndex = 3NextEnd WithNext IEnd Sub19. Highlight Cells with Comments
To highlight all the cells with comments use this macro.
Sub highlightCommentCells()Selection.SpecialCells(xlCellTypeComments).SelectSelection.Style= "Note"End Sub20. Highlight Alternate Rows in the Selection
By highlighting alternate rows, you can make your data easily readable, and for this, you can use below VBA code. It will simply highlight every alternate row in selected range.
Sub highlightAlternateRows()Dim rng As RangeFor Each rng In Selection.RowsIf rng.Row Mod 2 = 1 Thenrng.Style = "20% -Accent1"rng.Value = rng ^ (1 / 3)ElseEnd IfNext rngEnd Sub21. Highlight Cells with Misspelled Words
If you find hard to check all the cells for spelling error, then this code is for you. It will check each cell from the selection and highlight the cell where is a misspelled word.
Sub HighlightMisspelledCells()Dim rng As RangeFor Each rng In ActiveSheet.UsedRangeIf Not Application.CheckSpelling(word:=rng.Text) Thenrng.Style = "Bad"End IfNext rngEnd Sub22. Highlight Cells with Error in the Entire Worksheet
To highlight and count all the cells in which you have an error, this code will help you. Just run this code and it will return a message with the number error cells and highlight all the cells.
Sub highlightErrors()Dim rng As RangeDim i As IntegerFor Each rng In ActiveSheet.UsedRangeIf WorksheetFunction.IsError(rng) Theni = i + 1rng.Style = "bad"End IfNext rngMsgBox _"There are total " & i _& " error(s) in this worksheet."End Sub23. Highlight Cells with a Specific Text in Worksheet
This code will help you to count the cells which have a specific value which you will mention and after that highlight all those cells.
Sub highlightSpecificValues()Dim rng As rangeDim i As IntegerDim c As Variantc = InputBox("Enter Value To Highlight")For Each rng In ActiveSheet.UsedRangeIf rng = c Thenrng.Style = "Note"i = i + 1End IfNext rngMsgBox "There are total " & i & " " & c & " in this worksheet."End Sub24. Highlight all the Blank Cells Invisible Space
Sometimes there are some cells which are blank, but they have a single space and due to this, it’s really hard to identify them. This code will check all the cell in the worksheet and highlight all the cells which have a single space.
Sub blankWithSpace()Dim rng As RangeFor Each rng In ActiveSheet.UsedRangeIf rng.Value = " " Thenrng.Style = "Note"End IfNext rngEnd Sub25. Highlight Max Value in the Range
It will check all the selected cells and highlight the cell with the maximum value.
Sub highlightMaxValue()Dim rng As RangeFor Each rng In SelectionIf rng = WorksheetFunction.Max(Selection) Thenrng.Style = "Good"End IfNext rngEnd Sub26. Highlight Min Value in the Range
It will check all the selected cells and highlight the cell with the Minimum value.
Sub Highlight_Min_Value()Dim rng As RangeFor Each rng In SelectionIf rng = WorksheetFunction.Min(Selection) Thenrng.Style = "Good"End IfNext rngEnd Sub27. Highlight Unique Values
This code will highlight all the cells from the selection which has a unique value.
Sub highlightUniqueValues()Dim rng As RangeSet rng = Selectionrng.FormatConditions.DeleteDim uv As UniqueValuesSet uv = rng.FormatConditions.AddUniqueValuesuv.DupeUnique = xlUniqueuv.Interior.Color = vbGreenEnd Sub28. Highlight Difference in Columns
Using this code, you can highlight the difference between two columns (corresponding cells).
Sub columnDifference()Range("H7:H8,I7:I8").SelectSelection.ColumnDifferences(ActiveCell).SelectSelection.Style= "Bad"End Sub29. Highlight Difference in Rows
And by using this code you can highlight difference between two row (corresponding cells).
Sub rowDifference()Range("H7:H8,I7:I8").SelectSelection.RowDifferences(ActiveCell).SelectSelection.Style= "Bad"End SubPrinting Codes
30. Print Comments
Sub printComments()With ActiveSheet.PageSetup.printComments = xlPrintSheetEndEnd WithEnd SubUse this macro to activate settings to print cell comments in the end of the page. Let’s say you have 10 pages to print, after using this code you will get all the comments on 11th last page.
31. Print Narrow Margin
Use this VBA code to take a print with a narrow margin. When you run this macro it will automatically change margins to narrow.
Sub printNarrowMargin()With ActiveSheet.PageSetup.LeftMargin = Application.InchesToPoints (0.25).RightMargin = Application.InchesToPoints(0.25).TopMargin = Application.InchesToPoints(0.75).BottomMargin = Application.InchesToPoints(0.75).HeaderMargin = Application.InchesToPoints(0.3).FooterMargin = Application.InchesToPoints(0.3)End WithActiveWindow.SelectedSheets.PrintOut _Copies:=1, _Collate:=True, _IgnorePrintAreas:=FalseEnd Sub32. Print Selection
This code will help you print selected range. You don’t need to go to printing options and set printing range. Just select a range and run this code.
Sub printSelection()Selection.PrintOut Copies:=1, Collate:=TrueEnd Sub33. Print Custom Pages
Instead of using the setting from print options you can use this code to print custom page range. Let’s say you want to print pages from 5 to 10. You just need to run this VBA code and enter start page and end page.
Sub printCustomSelection()Dim startpage As IntegerDim endpage As Integerstartpage = _InputBox("Please Enter Start Page number.", "Enter Value")If Not WorksheetFunction.IsNumber(startpage) ThenMsgBox _"Invalid Start Page number. Please try again.", "Error"Exit SubEnd Ifendpage = _InputBox("Please Enter End Page number.", "Enter Value")If Not WorksheetFunction.IsNumber(endpage) ThenMsgBox _"Invalid End Page number. Please try again.", "Error"Exit SubEnd IfSelection.PrintOut From:=startpage, _To:=endpage, Copies:=1, Collate:=TrueEnd SubWorksheet Codes
34. 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 WorksheetFor Each ws In ThisWorkbook.WorksheetsIf ws.Name <> ThisWorkbook.ActiveSheet.Name Thenws.Visible = xlSheetHiddenEnd IfNext wsEnd SubRelated: VBA Functions List
35. Unhide all Hidden Worksheets
And if you want to un-hide all the worksheets which you have hide with previous code, here is the code for that.
Sub UnhideAllWorksheet()Dim ws As WorksheetFor Each ws In ActiveWorkbook.Worksheetsws.Visible = xlSheetVisibleNext wsEnd Sub36. 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 WorksheetFor Each ws In ThisWorkbook.WorksheetsIf ws.name <> ThisWorkbook.ActiveSheet.name ThenApplication.DisplayAlerts = Falsews.DeleteApplication.DisplayAlerts = TrueEnd IfNext wsEnd Sub37. Protect all Worksheets Instantly
If you want to protect your all worksheets in one go here is a code 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 ProtectAllWorskeets()Dim ws As WorksheetDim ps As Stringps = InputBox("Enter a Password.", vbOKCancel)For Each ws In ActiveWorkbook.Worksheetsws.Protect Password:=psNext wsEnd Sub38. 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 IntegerFor i = 1 To ActiveSheet.ChartObjects.CountWith ActiveSheet.ChartObjects(i).Width = 300.Height = 200End WithNext iEnd Sub39. Insert Multiple Worksheets
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 Integeri = _InputBox("Enter number of sheets to insert.", _"Enter Multiple Sheets")Sheets.Add After:=ActiveSheet, Count:=iEnd Sub40. Protect Worksheet
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, TrueEnd Sub41. Un-Protect Worksheet
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 Sub42. Sort Worksheets
This code will help you to sort worksheets in your workbook according to their name.
Sub SortWorksheets()Dim i As IntegerDim j As IntegerDim iAnswer As VbMsgBoxResultiAnswer = 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.CountFor j = 1 To Sheets.Count - 1If iAnswer = vbYes ThenIf UCase$(Sheets(j).Name) > UCase$(Sheets(j + 1).Name) ThenSheets(j).Move After:=Sheets(j + 1)End IfElseIf iAnswer = vbNo ThenIf UCase$(Sheets(j).Name) < UCase$(Sheets(j + 1).Name) Then Sheets(j).Move After:=Sheets(j + 1)End IfEnd IfNext jNext iEnd Sub43. Protect all the Cells with Formulas
To protect cell with formula with a single click you can use this code.
Sub lockCellsWithFormulas()With ActiveSheet.Unprotect.Cells.Locked = False.Cells.SpecialCells(xlCellTypeFormulas).Locked = True.Protect AllowDeletingRows:=TrueEnd WithEnd Sub44. Delete all Blank Worksheets
Run this code and it will check all the worksheets in the active workbook and delete if a worksheet is blank.
Sub deleteBlankWorksheets()Dim Ws As WorksheetOn Error Resume NextApplication.ScreenUpdating= FalseApplication.DisplayAlerts= FalseFor Each Ws In Application.WorksheetsIf Application.WorksheetFunction.CountA(Ws.UsedRange) = 0 ThenWs.DeleteEnd IfNextApplication.ScreenUpdating= TrueApplication.DisplayAlerts= TrueEnd Sub45. Unhide all Rows and Columns
Instead of unhiding rows and columns on by one manually you can use this code to do this in a single go.
Sub UnhideRowsColumns()Columns.EntireColumn.Hidden = FalseRows.EntireRow.Hidden = FalseEnd Sub46. Save Each Worksheet as a Single PDF
This code will simply save all the worksheets in a separate PDF file. You just need to change the folder name from the code.
Sub SaveWorkshetAsPDF()Dimws As WorksheetFor Each ws In Worksheetsws.ExportAsFixedFormat _xlTypePDF, _"ENTER-FOLDER-NAME-HERE" &; _ws.Name & ".pdf"Next wsEnd Sub47. Disable Page Breaks
To disable page breaks use this code. It will simply disable page breaks from all the open workbooks.
Sub DisablePageBreaks()Dim wb As WorkbookDim wks As WorksheetApplication.ScreenUpdating = FalseFor Each wb In Application.WorkbooksFor Each Sht In wb.WorksheetsSht.DisplayPageBreaks = FalseNext ShtNext wbApplication.ScreenUpdating = TrueEnd SubWorkbook Codes
These codes will help you to perform workbook level tasks in an easy way and with minimum efforts.
48. 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.
Sub FileBackUp()ThisWorkbook.SaveCopyAs Filename:=ThisWorkbook.Path & _"" & Format(Date, "mm-dd-yy") & " " & _ThisWorkbook.nameEnd SubIt will save 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.
49. 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.
Sub CloseAllWorkbooks()Dim wbs As WorkbookFor Each wbs In Workbookswbs.Close SaveChanges:=TrueNext wbEnd SubIf any of the worksheets is not saved, you’ll get a message to save it.
50. 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.
Sub CopyWorksheetToNewWorkbook()ThisWorkbook.ActiveSheet.Copy _Before:=Workbooks.Add.Worksheets(1)End SubIt’s a super time saver.
51. 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 ObjectDim OutMail As ObjectSet OutApp = CreateObject("Outlook.Application")Set OutMail = OutApp.CreateItem(0)With OutMail.to = "[email protected]".Subject = "Growth Report".Body = "Hello Team, Please find attached Growth Report.".Attachments.Add ActiveWorkbook.FullName.displayEnd WithSet OutMail = NothingSet OutApp = NothingEnd Sub52. Add Workbook to a Mail Attachment
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).ShowEnd Sub53. Welcome Message
You can use auto_open to perform a task on opening a file and all you have to do just name your macro “auto_open”.
Sub auto_open()MsgBox _"Welcome To ExcelChamps & Thanks for downloading this file."End Sub54. Closing Message
You can use close_open to perform a task on opening a file and 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 onexcelchamps.com"End Sub55. Count Open Unsaved Workbooks
Let’s you have 5-10 open workbooks; you can use this code to get the number of workbooks which are not saved yet.
Sub VisibleWorkbooks()Dim book As WorkbookDim i As IntegerFor Each book In WorkbooksIf book.Saved = False Theni = i + 1End IfNext bookMsgBox iEnd SubPivot Table Codes
56. Hide Pivot Table Subtotals
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 PivotTableDim pf As PivotFieldOn Error Resume NextSet pt = ActiveSheet.PivotTables(ActiveCell.PivotTable.Name)If pt Is Nothing ThenMsgBox "You must place your cursor inside of a PivotTable."Exit SubEnd IfFor Each pf In pt.PivotFieldspf.Subtotals(1) = Truepf.Subtotals(1) = FalseNext pfEnd Sub57. Refresh All Pivot Tables
A super quick method to refresh all pivot tables. Just run this code and all of your pivot tables in your workbook will be refresh in a single shot.
Sub vba_referesh_all_pivots()Dim pt As PivotTableFor Each pt In ActiveWorkbook.PivotTablespt.RefreshTableNext ptEnd Sub58. Create a Pivot Table
Follow this step-by-step guide to create a pivot table using VBA.
59. Auto 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 WorksheetDim Pivot_Sheet As WorksheetDim StartPoint As RangeDim DataRange As RangeDim PivotName As StringDim NewRange As StringDim LastCol As LongDim lastRow As Long'Set Pivot Table & Source WorksheetSet Data_Sheet = ThisWorkbook.Worksheets("PivotTableData3")Set Pivot_Sheet = ThisWorkbook.Worksheets("Pivot3")'Enter in Pivot Table NamePivotName = "PivotTable2"'Defining Staring Point & Dynamic RangeData_Sheet.ActivateSet StartPoint = Data_Sheet.Range("A1")LastCol = StartPoint.End(xlToRight).ColumnDownCell = StartPoint.End(xlDown).RowSet DataRange = Data_Sheet.Range(StartPoint, Cells(DownCell, LastCol))NewRange = Data_Sheet.Name & "!" & DataRange.Address(ReferenceStyle:=xlR1C1)'Change Pivot Table Data Source Range AddressPivot_Sheet.PivotTables(PivotName). _ChangePivotCache ActiveWorkbook. _PivotCaches.Create(SourceType:=xlDatabase, SourceData:=NewRange)'Ensure Pivot Table is RefreshedPivot_Sheet.PivotTables(PivotName).RefreshTable'Complete MessagePivot_Sheet.ActivateMsgBox "Your Pivot Table is now updated."End Sub60. Disable/Enable Get Pivot Data
To disable/enable GetPivotData function you need to go to the Excel options. But with this code you can do it in a single click.
Sub activateGetPivotData()Application.GenerateGetPivotData = TrueEnd SubSub deactivateGetPivotData()Application.GenerateGetPivotData = FalseEnd SubCharts Codes
61. Change Chart Type
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.
Sub ChangeChartType()ActiveChart.ChartType = xlColumnClusteredEnd SubThere are different codes for different types, you can find all those types from here.
62. Paste Chart as an Image
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.CopyActiveSheet.Range("A1").SelectActiveSheet.Pictures.Paste.SelectEnd Sub63. Add 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 Varianti = InputBox("Please enter your chart title", "Chart Title")On Error GoTo LastActiveChart.SetElement (msoElementChartTitleAboveChart)ActiveChart.ChartTitle.Text = iLast:Exit SubEnd SubAdvanced Codes
64. Save Selected Range as a PDF
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 PivotTableDim pf As PivotFieldOn Error Resume NextSet pt = ActiveSheet.PivotTables(ActiveCell.PivotTable.name)If pt Is Nothing ThenMsgBox "You must place your cursor inside of a PivotTable."Exit SubEnd IfFor Each pf In pt.PivotFieldspf.Subtotals(1) = Truepf.Subtotals(1) = FalseNext pfEnd Sub65. 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.
Sub TableofContent()Dim i As LongOn Error Resume NextApplication.DisplayAlerts = FalseWorksheets("Table of Content").DeleteApplication.DisplayAlerts = TrueOn Error GoTo 0ThisWorkbook.Sheets.Add Before:=ThisWorkbook.Worksheets(1)ActiveSheet.Name = "Table of Content"For i = 1 To Sheets.CountWith ActiveSheet.Hyperlinks.Add _Anchor:=ActiveSheet.Cells(i, 1), _Address:="", _SubAddress:="'" & Sheets(i).Name & "'!A1", _ScreenTip:=Sheets(i).Name, _TextToDisplay:=Sheets(i).NameEnd WithNext iEnd SubWhen you run this code, it will create a new worksheet and create a index of worksheets with a hyperlink to them.
66. 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 = FalseSelection.CopyActiveSheet.Pictures.Paste.SelectEnd Sub67. Insert a Linked Picture
This VBA code will convert your selected range into a linked picture and you can use that image anywhere you want.
Sub LinkedPicture()Selection.CopyActiveSheet.Pictures.Paste(Link:=True).SelectEnd Sub68. Use Text to Speech
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.SpeakEnd Sub69. Activate Data Entry Form
There is a default data entry form which you can use for data entry.
Sub DataForm()ActiveSheet.ShowDataFormEnd Sub70. Use Goal Seek
Goal Seek can be super helpful for you to solve complex problems. Learn more about goal seek from here before you use this code.
Sub GoalSeekVBA()Dim Target As LongOn Error GoTo ErrorhandlerTarget = InputBox("Enter the required value", "Enter Value")Worksheets("Goal_Seek").ActivateWith ActiveSheet.Range("C7").GoalSeek_ Goal:=Target, _ChangingCell:=Range("C2")End WithExit SubErrorhandler: MsgBox ("Sorry, value is not valid.")End Sub71. VBA Code to Search on Google
Sub SearchWindow32()Dim chromePath As StringDim search_string As StringDim query As Stringquery = InputBox("Enter here your search here", "Google Search")search_string = querysearch_string = Replace(search_string, " ", "+")'Uncomment the following line for Windows 64 versions and comment out Windows 32 versions''chromePath = "C:Program FilesGoogleChromeApplicationchrome.exe"'Uncomment the following line for Windows 32 versions and comment out Windows 64 versions'chromePath = "C:Program Files (x86)GoogleChromeApplicationchrome.exe"Shell (chromePath & " -url http://google.com/#q=" & search_string)End SubFormula Codes
72. 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 RangeDim MyCell As RangeSelect Case _MsgBox("You Can't Undo This Action. " _& "Save Workbook First?", vbYesNoCancel, _"Alert")Case Is = vbYesThisWorkbook.SaveCase Is = vbCancelExit SubEnd SelectSet MyRange = SelectionFor Each MyCell In MyRangeIf MyCell.HasFormula ThenMyCell.Formula = MyCell.ValueEnd IfNext MyCellEnd Sub73. Remove Spaces from Selected Cells
One of the most useful macros from this list. It will check your selection and then remove all the extra spaces from that.
Sub RemoveSpaces()Dim myRange As RangeDim myCell As RangeSelect Case MsgBox("You Can't Undo This Action. " _& "Save Workbook First?", _vbYesNoCancel, "Alert")Case Is = vbYesThisWorkbook.SaveCase Is = vbCancelExit SubEnd SelectSet myRange = SelectionFor Each myCell In myRangeIf Not IsEmpty(myCell) ThenmyCell = Trim(myCell)End IfNext myCellEnd Sub74. 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 and number of characters to remove from the text string.
Public Function removeFirstC(rng As String, cnt As Long)removeFirstC = Right(rng, Len(rng) - cnt)End FunctionIt 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.
75. Add Insert Degree Symbol in Excel
Let’s say you have a list of numbers in a column and you want to add degree symbol with all of them.
Sub degreeSymbol( )Dim rng As RangeFor Each rng In Selectionrng.SelectIf ActiveCell <> "" ThenIf IsNumeric(ActiveCell.Value) ThenActiveCell.Value = ActiveCell.Value & "°"End IfEnd IfNextEnd Sub76. 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 Stringrvrse = VBA.strReverse(cell.Value)End Function77. Activate R1C1 Reference Style
This macro code will help you to activate R1C1 reference style without using Excel options.
Sub ActivateR1C1()If Application.ReferenceStyle = xlA1 ThenApplication.ReferenceStyle = xlR1C1ElseApplication.ReferenceStyle = xlR1C1End IfEnd Sub78. Activate A1 Reference Style
This macro code will help you to activate A1 reference style without using Excel options.
Sub ActivateA1()If Application.ReferenceStyle = xlR1C1 ThenApplication.ReferenceStyle = xlA1ElseApplication.ReferenceStyle = xlA1End IfEnd Sub79. Insert Time Range
With this code, you can insert a time range in sequence from 00:00 to 23:00.
Sub TimeStamp()Dim i As IntegerFor i = 1 To 24ActiveCell.FormulaR1C1 = i & ":00"ActiveCell.NumberFormat = "[$-409]h:mm AM/PM;@"ActiveCell.Offset(RowOffset:=1, ColumnOffset:=0).SelectNext iEnd Sub80. 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. Simply select the range of cells and run this macro.
Sub date2day()Dim tempCell As RangeSelection.Value = Selection.ValueFor Each tempCell In SelectionIf IsDate(tempCell) = True ThenWith tempCell.Value = Day(tempCell).NumberFormat = "0"End WithEnd IfNext tempCellEnd Sub81. Convert Date into Year
This code will convert dates into years.
Sub date2year()Dim tempCell As RangeSelection.Value = Selection.ValueFor Each tempCell In SelectionIf IsDate(tempCell) = True ThenWith tempCell.Value = Year(tempCell).NumberFormat = "0"End WithEnd IfNext tempCellEnd Sub82. Remove Time from Date
If you have time with the date and you want to remove it then you can use this code.
Sub removeTime()Dim Rng As RangeFor Each Rng In SelectionIf IsDate(Rng) = True ThenRng.Value = VBA.Int(Rng.Value)End IfNextSelection.NumberFormat = "dd-mmm-yy"End Sub83. Remove Date from Date and Time
It will return only time from a date and time value.
Sub removeDate()Dim Rng As RangeFor Each Rng In SelectionIf IsDate(Rng) = True ThenRng.Value = Rng.Value - VBA.Fix(Rng.Value)End IfNextSelection.NumberFormat = "hh:mm:ss am/pm"End Sub84. Convert to Upper Case
Select the cells and run this code. It will check each and every cell of selected range and then convert it into upper case text.
Sub convertUpperCase()Dim Rng As RangeFor Each Rng In SelectionIf Application.WorksheetFunction.IsText(Rng) ThenRng.Value = UCase(Rng)End IfNextEnd Sub85. Convert to Lower Case
This code will help you to convert selected text into lower case text. Just select a range of cells where you have text and run this code. If a cell has a number or any value other than text that value will remain same.
Sub convertLowerCase()Dim Rng As RangeFor Each Rng In SelectionIf Application.WorksheetFunction.IsText(Rng) ThenRng.Value= LCase(Rng)End IfNextEnd Sub86. Convert to Proper Case
And this code will convert selected text into the proper case where you have the first letter in capital and rest in small.
Sub convertProperCase()Dim Rng As RangeFor Each Rng In SelectionIf WorksheetFunction.IsText(Rng) ThenRng.Value = WorksheetFunction.Proper(Rng.Value)End IfNextEnd Sub87. Convert to Sentence Case
In text case, you have the first letter of the first word in capital and rest all in words in small for a single sentence and this code will help you convert normal text into sentence case.
Sub convertTextCase()Dim Rng As RangeFor Each Rng In SelectionIf WorksheetFunction.IsText(Rng) ThenRng.Value = UCase(Left(Rng, 1)) & LCase(Right(Rng, Len(Rng) - 1))End IfNext RngEnd Sub88. Remove a Character from Selection
To remove a particular character from a selected cell you can use this code. It will show you an input box to enter the character you want to remove.
Sub removeChar()Dim Rng As RangeDim rc As Stringrc = InputBox("Character(s) to Replace", "Enter Value")For Each Rng In SelectionSelection.Replace What:=rc, Replacement:=""NextEnd Sub89. Word Count from Entire Worksheet
It can help you to count all the words from a worksheet.
Sub Word_Count_Worksheet()Dim WordCnt As LongDim rng As RangeDim S As StringDim N As LongFor Each rng In ActiveSheet.UsedRange.CellsS = Application.WorksheetFunction.Trim(rng.Text)N = 0If S <> vbNullString ThenN = Len(S) - Len(Replace(S, " ", "")) + 1End IfWordCnt = WordCnt + NNext rngMsgBox "There are total " _& Format(WordCnt, "#,##0") & _" words in the active worksheet"End Sub90. Remove the Apostrophe from a Number
If you have numeric data with an apostrophe before each number, you run this code to remove it.
Sub removeApostrophes()Selection.Value = Selection.ValueEnd Sub91. Remove Decimals from Numbers
This code will help you remove all the decimals from the numbers from the selected range.
Sub removeDecimals()Dim lnumber As DoubleDim lResult As LongDim rng As RangeFor Each rng In Selectionrng.Value = Int(rng)rng.NumberFormat = "0"Next rngEnd Sub92. Multiply all the Values by a Number
Let’s have a list of numbers, and you want to multiply all the numbers with a particular one.
Sub addNumber()Dim rng As RangeDim i As Integeri = InputBox("Enter number to multiple", "Input Required")For Each rng In SelectionIf WorksheetFunction.IsNumber(rng) Thenrng.Value = rng + iElseEnd IfNext rngEnd SubTo use this code, Select that range of cells and run this code. It will first ask you for the number with whom you want to multiply and then instantly multiply all the numbers with it.
93. Add a Number in all the Numbers
Just like multiplying, you can also add a number into a set of numbers.
Sub addNumber()Dim rng As RangeDim i As Integeri = InputBox("Enter number to multiple", "Input Required")For Each rng In SelectionIf WorksheetFunction.IsNumber(rng) Thenrng.Value = rng + iElseEnd IfNext rngEnd Sub94. Calculate the Square Root
You can use this code to calculate square root without applying a formula. It will simply check all the selected cells and convert numbers to their square root.
Sub getSquareRoot()Dim rng As RangeDim i As IntegerFor Each rng In SelectionIf WorksheetFunction.IsNumber(rng) Thenrng.Value = Sqr(rng)ElseEnd IfNext rngEnd Sub95. Calculate the Cube Root
You can use this code to calculate cube root without applying a formula. It will simply check all the selected cells and convert numbers to their cube root.
Sub getCubeRoot()Dim rng As RangeDimi As IntegerFor Each rng In SelectionIf WorksheetFunction.IsNumber(rng) Thenrng.Value = rng ^ (1 / 3)ElseEnd IfNextrngEnd Sub96. Add A-Z Alphabets in a Range
Just like serial numbers you can also insert alphabets in your worksheet. Below are the codes which you can use.
Sub addsAlphabets1()Dim i As IntegerFor i = 65 To 90ActiveCell.Value = Chr(i)ActiveCell.Offset(1, 0).SelectNext iEnd SubSub addsAlphabets2()Dim i As IntegerFor i = 97 To 122ActiveCell.Value = Chr(i)ActiveCell.Offset(1, 0).SelectNext iEnd Sub97. Convert Roman Numbers into Arabic Numbers
Sometimes, it’s really hard to understand Roman numbers as serial numbers. This code will help you to convert Roman numbers into Arabic numbers.
Sub convertToNumbers()Dim rng As RangeSelection.Value = Selection.ValueFor Each rng In SelectionIf Not WorksheetFunction.IsNonText(rng) Thenrng.Value = WorksheetFunction.Arabic(rng)End IfNext rngEnd Sub98. Remove Negative Signs
This code will check all the cells in the selection and convert all the negative numbers into positive ones. Just select a range and run this code.
Sub removeNegativeSign()Dim rng As RangeSelection.Value = Selection.ValueFor Each rng In SelectionIf WorksheetFunction.IsNumber(rng) Thenrng.Value = Abs(rng)End IfNext rngEnd Sub99. Replace Blank Cells with Zeros
For data with blank cells, you can use the code below to add zeros in all those cells. It makes easier to use those cells in further calculations.
Sub replaceBlankWithZero()Dim rng As RangeSelection.Value = Selection.ValueFor Each rng In SelectionIf rng = "" Or rng = " " Thenrng.Value = "0"ElseEnd IfNext rngEnd Sub100. Create a Simple Timer
Sub SimpleTimer() Dim countDown As Date countDown = Now + TimeValue("00:01:00") ' Set timer for 1 minute Do Until Now >= countDown DoEvents Loop MsgBox "Time's up!"End Sub101. Convert Text to Columns Automatically
Sub TextToColumnsAuto() Dim rng As Range Set rng = ThisWorkbook.Sheets("Sheet1").Range("A1:A100") rng.TextToColumns Destination:=rng, DataType:=xlDelimited, Comma:=TrueEnd Sub102. Unprotect All Sheets in a Workbook
Sub UnprotectSheets() Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets ws.Unprotect Password:="password" Next wsEnd Sub103. Protect All Sheets in a Workbook
Sub CombineWorkbooks() Dim FilesToOpen Dim x As Integer FilesToOpen = Application.GetOpenFilename(FileFilter:="Microsoft Excel Files (*.xls; *.xlsx; *.xlsm), *.xls; *.xlsx; *.xlsm", MultiSelect:=True, Title:="Files to Merge") If TypeName(FilesToOpen) = "Boolean" Then Exit Sub x = 1 While x <= UBound(FilesToOpen) Workbooks.Open Filename:=FilesToOpen(x) Sheets().Move After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count) x = x + 1 WendEnd Sub104. Combine Multiple Excel Files Into One Workbook
Sub ProtectSheets() Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets ws.Protect Password:="password" Next wsEnd Sub105. Send an Email via Outlook
Sub SendEmail() Dim OutApp As Object Dim OutMail As Object Set OutApp = CreateObject("Outlook.Application") Set OutMail = OutApp.CreateItem(0) With OutMail .To = "[email protected]" .CC = "" .BCC = "" .Subject = "This is the Subject Line" .Body = "Hello World!" .Send End With Set OutMail = Nothing Set OutApp = NothingEnd Sub106. Insert Multiple Rows Between Each Row in a Worksheet
Sub InsertRows() Dim i As Long For i = ThisWorkbook.Sheets("Sheet1").UsedRange.Rows.Count To 1 Step -1 ThisWorkbook.Sheets("Sheet1").Rows(i + 1).Resize(2).Insert Next iEnd Sub107. Automatically Save a Backup Copy of a Workbook
Sub SaveBackup() Dim backupPath As String backupPath = "C:\Backup\MyWorkbook_" & Format(Now(), "yyyymmdd_hhmmss") & ".xlsm" ThisWorkbook.SaveCopyAs backupPathEnd Sub108. Delete All Charts in a Worksheet
Sub DeleteCharts() Dim cht As ChartObject For Each cht In ActiveSheet.ChartObjects cht.Delete Next chtEnd Sub109. Automatically Close Workbook After Inactivity
Sub AutoClose() Dim countDown As Date countDown = Now + TimeValue("00:10:00") ' Set timer for 10 minutes Do Until Now >= countDown If Not Application.Interactive Then Exit Sub DoEvents Loop ThisWorkbook.Close SaveChanges:=FalseEnd Sub110. Export Each Worksheet to a New Workbook
Sub ExportSheetsToWorkbooks() Dim ws As Worksheet For Each ws In ThisWorkbook.Worksheets ws.Copy ActiveWorkbook.SaveAs "C:\ExportedSheets\" & ws.Name & ".xlsx" ActiveWorkbook.Close False Next wsEnd Sub111. Create a Directory from VBA
Sub CreateDirectory() Dim path As String path = "C:\NewFolder" If Not Dir(path, vbDirectory) <> "" Then MkDir path End IfEnd Sub112. Convert Numbers to Words (Functions)
Function NumberToWords(ByVal MyNumber) Dim Units As String, Teens As String, Tens As String Dim Result As String ' Arrays for converting number to words Units = "|One|Two|Three|Four|Five|Six|Seven|Eight|Nine" Teens = "|Eleven|Twelve|Thirteen|Fourteen|Fifteen|Sixteen|Seventeen|Eighteen|Nineteen" Tens = "|Ten|Twenty|Thirty|Forty|Fifty|Sixty|Seventy|Eighty|Ninety" ' Logic to convert number to words goes here ' Return the result as a string Result = "Logic not implemented" NumberToWords = ResultEnd Sub113. Add a Watermark to a Worksheet
Sub AddWatermark() ActiveSheet.Shapes.AddTextEffect(msoTextEffect1, "Confidential", "Arial", 50, msoFalse, msoFalse, 100, 100).Select With Selection.ShapeRange.Fill .Visible = msoTrue .ForeColor.RGB = RGB(217, 217, 217) .Transparency = 0.5 End WithEnd Sub114. Sort Data in a Worksheet Automatically
Sub AutoSort() With ThisWorkbook.Sheets("Sheet1").Range("A1:D100") .Sort Key1:=.Cells(1, 1), Order1:=xlAscending, Header:=xlYes End WithEnd Sub115. Print All Workbooks in a Folder
Sub PrintAllWorkbooks() Dim folderPath As String Dim filename As String folderPath = "C:\MyFolder\" filename = Dir(folderPath & "*.xls*") Do While filename <> "" Workbooks.Open Filename:=folderPath & filename ActiveWorkbook.PrintOut Copies:=1 ActiveWorkbook.Close False filename = Dir() LoopEnd Sub116. Highlight Cells That Contain Formulas
Sub HighlightFormulas() Dim cell As Range For Each cell In ActiveSheet.UsedRange If cell.HasFormula Then cell.Interior.Color = RGB(255, 255, 0) End If Next cellEnd SubMore Codes and Example
- Create a User Defined Function [UDF] in Excel using VBA
- VBA Interview Questions
- Add a Comment in a VBA Code (Macro)
- Add a Line Break in a VBA Code (Single Line into Several Lines)
- Add a New Line (Carriage Return) in a String in VBA
- Record a Macro in Excel
- VBA Exit Sub Statement
- VBA Immediate Window (Debug.Print)
- VBA Module
- VBA Objects
- VBA With
- Add Developer Tab on Excel Ribbon | Windows + Mac
- Count Rows using VBA in Excel
- Excel VBA Font (Color, Size, Type, and Bold)
- Excel VBA Hide and Unhide a Column or a Row
- Excel VBA Range – Working with Range and Cells in VBA
- Apply Borders on a Cell using VBA in Excel
- Find Last Row, Column, and Cell using VBA in Excel
- Insert a Row using VBA in Excel
- Merge Cells in Excel using a VBA Code
- Select a Range/Cell using VBA in Excel
- SELECT ALL the Cells in a Worksheet using a VBA Code
- ActiveCell in VBA in Excel
- Special Cells Method in VBA in Excel
- UsedRange Property in VBA in Excel
- VBA AutoFit (Rows, Column, or the Entire Worksheet)
- VBA ClearContents (from a Cell, Range, or Entire Worksheet)
- VBA Copy Range to Another Sheet + Workbook
- VBA Enter Value in a Cell (Set, Get and Change)
- VBA Insert Column (Single and Multiple)
- VBA Named Range | (Static + from Selection + Dynamic)
- VBA Range Offset
- VBA Sort Range | (Descending, Multiple Columns, Sort Orientation
- VBA Wrap Text (Cell, Range, and Entire Worksheet)
- Extract Hyperlink Address (URL) VBA
- CLEAR an Entire Sheet using VBA in Excel
- Copy and Move a Sheet in Excel using VBA
- COUNT Sheets using VBA in Excel
- DELETE a SHEET using VBA in Excel
- Hide & Unhide a Sheet using VBA in Excel
- PROTECT and UNPROTECT a Sheet using VBA in Excel
- RENAME a Sheet using VBA in Excel
- Write a VBA Code to Create a New Sheet in Excel (Macro)
- VBA Worksheet Object -Working with Excel Worksheet in VBA
- Activate a Sheet using VBA
- Copy an Excel File (Workbook) using VBA – Macro Code
- VBA Activate Workbook (Excel File)
- VBA Close Workbook (Excel File)
- VBA Combine Workbooks (Excel Files)
- VBA Create New Workbook (Excel File)
- VBA Delete Workbook (Excel File)
- VBA Open Workbook (Excel File)
- VBA Protect/Unprotect Workbook (Excel File)
- VBA Rename Workbook (Excel File)
- VBA Save Workbook (Excel File)
- VBA ThisWorkbook (Current Excel File)
- VBA Workbook – A Guide to Work with Workbooks in VBA
- Declare Global Variable (Public) in VBA
- Use a Range or a Cell as a Variable in VBA
- Option Explicit Statement in VBA
- Variable in a Message Box
- VBA Constants
- VBA Dim Statement
- VBA Variables (Declare, Data Types, and Scope)
- VBA Add New Value to the Array
- VBA Array
- VBA Array Length (Size)
- VBA Array with Strings
- VBA Clear Array (Erase)
- VBA Dynamic Array
- VBA Loop Through an Array
- VBA Multi-Dimensional Array
- VBA Range to an Array
- VBA Search for a Value in an Array
- VBA Sort Array
- Average Values in Excel using VBA
- Get Today’s Date and Current Time using VBA
- Sum Values in Excel using VBA
- Match Function in VBA
- MOD in VBA
- Random Number
- VBA Calculate (Cell, Range, Row, & Workbook)
- VBA Concatenate
- VBA Worksheet Function (Use Excel Functions in a Macro)
- VBA Check IF a Sheet Exists
- VBA Check IF a Cell is Empty + Multiple Cells
- VBA Check IF a Workbook Exists in a Folder (Excel File)
- VBA Check IF a Workbook is Open (Excel File)
- VBA Exit IF
- VBA IF – IF Then Else Statement
- VBA IF And (Test Multiple Conditions)
- VBA IF Not
- VBA IF OR (Test Multiple Conditions)
- VBA Nested IF
- VBA Select Case
- VBA Automation Error (Error 440)
- VBA Error 400
- VBA ERROR Handling
- VBA Invalid Procedure Call Or Argument Error (Error 5)
- VBA Object Doesn’t Support this Property or Method Error (Error 438)
- VBA Object Required Error (Error 424)
- VBA Out of Memory Error (Error 7)
- VBA Overflow Error (Error 6)
- VBA Runtime Error (Error 1004)
- VBA Subscript Out of Range Runtime Error (Error 9)
- VBA Type Mismatch Error (Error 13)
- Excel VBA Do While Loop and (Do Loop While) – A Guide
- Loop Through All the Sheets using VBA in Excel
- Loop Through a Range using VBA (Columns, Row, and UsedRange)
- VBA FOR LOOP (For Next, For Each) – The Guide + Examples
- VBA GoTo Statement
- VBA Loops (Beginner to Advanced) – A Guide
- Input Box in VBA
- VBA Create and Write to a Text File
- VBA ScreenUpdating
- VBA Status Bar (Hide, Show, and Progress)
- VBA Wait and Sleep Commands to Pause and Delay
- Save an Excel Macro-Enabled Workbook (.xlsm File Type)
- Search on Google using a VBA
Từ khóa » Visual Basic Excel Macro Programming
-
What Is A VBA Macro In Excel? - Corporate Finance Institute
-
Getting Started With VBA In Office - Microsoft Docs
-
VBA - Excel Macros - Tutorialspoint
-
Excel VBA Tutorial - Easy Excel Programming
-
Excel Macros & VBA - Tutorial For Beginners - YouTube
-
Excel VBA Beginner Tutorial (Part 1 Of 3) - YouTube
-
Excel VBA Tutorial For Beginners: Learn In 3 Days - Guru99
-
Cách Sử Dụng Macro Và VBA Trong Microsoft Excel
-
VBA Code Examples For Excel
-
Excel VBA Tutorial With Real-time VBA Examples | Simplilearn
-
Bắt đầu Với Excel Macros Và Lập Trình VBA
-
What Is VBA? The Excel Macro Language
-
Excel VBA Tutorial – How To Write Code In A Spreadsheet Using ...
-
Section 1: Programming In Excel (Macros) - Excel VBA