40 Ready to Use Excel VBA and Macros for beginners

Get access to 40 Ready To Use Excel VBA Macros that you can cut and paste straight away to your Excel workbooks & re

201 33

English Pages 40 [50] Year 2023

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

40 Ready to Use Excel VBA and Macros for beginners

  • Commentary
  • 40 Ready to Use Excel VBA and Macros

Table of contents :
Introduction
Why do you need macros?
VBA Examples to copy and paste
Copy Data from One Sheet to Another with a Loop
Hide All Worksheets Except the Active Sheet
Sort Worksheets Alphabetically Using VBA
Format All Charts at One Go
Automatic Data Validation
Merge Cells Across Multiple Columns in One Go
Freeze The First Row Of A Sheet Using VBA
Add gridlines to All Sheets in One Go
Change the Color of Every Other Row In One Go
Create Interactive Dashboards with VBA
Hide Unused Cells with VBA
Include Sum Of Cells In The Bottom Row
Automatically Insert Filenames Into Cells On Any Worksheet
Add Headers and Footers to All Worksheets
Highlight Cells with Duplicate Values
Freeze The Top Row of Any Worksheet
Find All Text Strings in Any Worksheet
Insert a Date and Time Stamp
Protect or Unprotect Any Worksheet
Insert a Hyperlink into Any Cell
Copy Existing Worksheets Into Another Workbook
Refresh All Pivot Tables
Delete All Unused Cells from All Worksheets
Hide or Unhide Any Sheet
Insert a New Column in Active Sheet
Sum All Values in a Column
Split Text into Different Cells
Replace Values in Multiple Columns
Create Chart from Data Range
Sort Data by Specified Order
Delete Blank Rows
Copy and Paste in a Range
Validate Data with Data Validation List
Merge Cells in a Range
Copy Entire Column
Conclusion

Citation preview

Introduction Macros are small programs that can be used to automate tasks in Excel. They allow you to take a repetitive task and execute it with the click of a button, rather than manually performing each step. 1) Recording Macros: This is the simplest way to create macros and involves recording your own actions within Excel. To do this, go to View->Macros->Record Macro. Give your macro a name and optionally assign it a shortcut key for easier access. Then start entering commands into Excel which will be recorded by the macro every time you hit enter or click an action button. When finished, stop the recording and save the macro. 2) Automatically Running Macros: Instead of having to manually run macros every time, you can also set them up to run automatically. You can do this by going to View->Macros->Options and then clicking the “Run macro on open” option. This will allow your macro to execute every time you open the workbook containing your macro. 3) Using Conditions in Macros: Excel allows you to create macros that use conditions such as IF/THEN statements, which can be used to make your code more dynamic and efficient. For example, if you want a macro to copy data into cells based on certain criteria, you can write an IF statement within the macro so it only copies the data when certain conditions are met. 4) Debugging Macros: When creating and running macros, you may run into issues that can be difficult to identify and solve. In order to debug your macros, you can use the “Step Into” option in Excel which allows you to step through your macro line by line so you can figure out where any errors are occurring. 5) Using Loops in Macros: You can use loops in your macros to repeat commands until a certain condition is met or an end goal has been

achieved. For example, if you want to copy data from one sheet to another multiple times, you can set up a loop within the macro so it will automatically iterate for each time the command needs to be executed.

6) Working with Variables: Variables allow you store information that can be used across multiple macros. For example, if you have data in one cell that needs to be used throughout your workbook, you can store it as a variable so it can be easily accessed and manipulated within different sections of code. 7) Accessing Other Workbooks: You can also use macros to access information from other Excel files. To do this, simply open the other file and then write your macro code using the “ActiveWorkbook” command which will allow the macro to interact with both workbooks simultaneously. 8) Working With Formulas: Macros are not just limited to copying and pasting data; they can also execute formulas on data as well. This is useful when dealing with large datasets that require a lot of calculations which would be tedious to do manually. 9) Working With Charts: Macros can also create and manipulate charts within Excel in order to make data more easily understandable. This is especially useful for presenting data to stakeholders as it makes complex numbers easier to understand at-a-glance. 10) Working with Pivot Tables: Macros are able to take large datasets and organize them into meaningful summaries using pivot tables. This is especially useful when trying to find trends or anomalies within your data that wouldn’t be obvious by just reviewing the raw values. By leveraging macros, you can quickly automate a wide variety of tasks in Excel that would otherwise take much longer if done

manually. This makes it possible to process data much more efficiently, allowing you to get the most out of your spreadsheets. With a little practice and knowledge, you can become an expert at creating powerful and efficient Excel macros that will make your life much easier. However, remember to always thoroughly debug your macros before using them as any errors could cause unexpected results or even corrupt the entire workbook. By taking these precautions, you can ensure that your valuable time is not wasted and that your data remains secure. Python also has a similar ability for automation called scripting. Scripting allows you to create automated processes that can be used to quickly complete tedious tasks with minimal effort. This can be especially useful if you need to do the same task repeatedly or if you are integrating different systems together. Python scripts are written in text files and then executed through the terminal, which makes them very easy to use and maintain. So if you’re looking for an easier way to automate your workflows, consider giving Python scripting a try! Good luck!

Why do you need macros? VBA macros can be used in Excel to perform powerful actions and make life easier. By using the macro code examples provided, you can quickly and easily learn how to delete blank rows, copy and paste in a range, validate data with a data validation list, merge cells in a range, and copy an entire column. Give them a try and see for yourself just how helpful VBA macros can be! If you’re looking for more macro codes or ideas for other advanced VBA excel macros you need to use with coding, consider doing some research online or reaching out to colleagues who may have experience with this type of programming. With so many possibilities available, you’ll find plenty of ways to automate your tasks and speed up your This content has been written to provide information about 50 excel macros that can be used with coding. The macros discussed range from simple delete rows, copy and pasting ranges, validating data with validation lists, merging cells in a range, to copying an entire column. Advanced VBA macros are also mentioned as an option for those who want to automate tedious tasks quickly and easily. This content encourages readers to try out the different excel macros to save time on projects.

VBA Examples to copy and paste Unhide All Worksheets at One Go If you are working in a workbook that has multiple hidden sheets, you need to unhide these sheets one by one. This could take some time in case there are many hidden sheets. Here is the code that will unhide all the worksheets in the workbook.

Sub UnhideAllWorksheets() For Each ws In ThisWorkbook.Sheets ws.Visible = True Next ws End Sub

Copy Data from One Sheet to Another with a Loop If you need to copy data from one sheet and paste it into another sheet multiple times, this can be done easily with the help of loops. The following code will copy the content from Sheet1 and paste it into Sheet2 for 3 times. Sub CopyDataWithLoop() For i = 1 To 3 Sheets("Sheet1").Range("A1:B10").Copy Sheets("Sheet2").Range("C" & (i*10)+1).PasteSpecial xlPasteValues Next i

End Sub

These are some of the many uses of macros to help you automate tasks in Excel.

Hide All Worksheets Except the Active Sheet If you’re working on a report or dashboard and you want to hide all the worksheet except the one that has the report/dashboard, you can use this macro code. Sub HideAllWorksheetsExceptActive() Dim ws As Worksheet

For Each ws In ThisWorkbook.Sheets If ws.Name ActiveSheet.Name Then ws.Visible = False End If Next ws End Sub

With the help of this macro, you can quickly hide all the worksheets except for the one that is active at the moment in just a few clicks! So now you don’t have to manually go through every sheet and hide it one by one! Give it a try!

Sort Worksheets Alphabetically Using VBA If you have a workbook with many worksheets and you want to sort these alphabetically, this macro code can come in really handy. This could be the case if you have sheet names as years or employee names or product names. Sub SortWorksheetsAlphabetically() Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets If Not Intersect(ws.UsedRange, ws.Range("A1")) Is Nothing Then ActiveWorkbook.Sheets(ws.Name).Move After:= _ Sheets(ActiveWorkbook.Sheets.Count) End If Next ws

Application.DisplayAlerts = False Call Sort_Worksheets_Alphabetically Application.DisplayAlerts = True End Sub

With the help of this macro code, you can easily sort all the worksheets of a workbook alphabetically. This will make navigation through your workbook much easier and faster! These are just some of the many Excel macros that you can learn to help you save time, improve productivity, and maximize accuracy in your spreadsheets. By taking the time to understand how VBA works and understanding when to use these macros, you can easily leverage their power to automate and simplify complex tasks.

Format All Charts at One Go Do you have multiple charts in an Excel sheet? Formatting all of them one by one could take up a lot of time. Here is an easy macro code that will help you quickly format all the charts at once. You need to specify the font size and type in the macro and all of the charts will be formatted accordingly. Sub FormatAllCharts() Dim cht As ChartObject For Each cht In ActiveSheet.ChartObjects cht.Activate With ActiveChart .Axes(xlCategory).TickLabels.Font.Size = 14 .Axes(xlCategory).TickLabels.Font.Name = "Arial" End With Next cht End Sub

This is a great way to save time if you have multiple charts that need to be formatted similarly! Give it a try and see how quickly you can format multiple charts. Now that you’ve seen a few different examples of Excel macros, try

writing your own to see how they can help you save time and automate tasks in Excel. Good luck!

Automatic Data Validation If you work with lots of data, sometimes it is necessary to have some kind of data validation process. This macro code helps you do just that. It checks the data entered against certain criteria (like length or type) and only allows valid entries. Sub AutoDataValidation() Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets With ws .Range("F1", .Cells(Rows.Count, "A").End(xlUp)).Validation _ .Add Type:=xlValidateWholeNumber, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:="0", Formula2:="100" End With Next ws End Sub

By using this macro code to add data validation rules to a worksheet, you can quickly and easily ensure that only valid entries are entered into the sheet. This is especially useful when dealing with large and complex datasets!

Merge Cells Across Multiple Columns in One Go If you have multiple columns of data that need to be merged together, manually merging each one can be quite time consuming. This macro code helps you to quickly merge two or more columns of data into one cell in just a few steps. Sub MergeCells() Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets With ws .Range("A1:D1").Merge End With Next ws End Sub

With the help of this macro, you can merge cells across multiple columns in no time at all!

Freeze The First Row Of A Sheet Using VBA When working with a large spreadsheet, it is often helpful to freeze the first row so that when you scroll down, the column headings are still visible. This macro code can help you do just that. Sub FreezeFirstRow() Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets With ws .Rows("1:1").Select .Window.FreezePanes = True End With Next ws End Sub

Add gridlines to All Sheets in One Go Are you working with multiple sheets, but want the same design for each of them? Rather than manually adding gridlines to each sheet, this macro code quickly adds gridlines to all the worksheets in your Excel file. Sub AddGridLines() Dim ws As Worksheet

For Each ws In ThisWorkbook.Sheets With ws .Cells.Select Selection.Borders(xlDiagonalDown).LineStyle = xlNone Selection.Borders(xlDiagonalUp).LineStyle = xlNone With Selection.Borders(xlEdgeLeft) .LineStyle = xlContinuous .Weight = xlMedium End With With Selection.Borders(xlEdgeTop) .LineStyle = xlContinuous

.Weight = xlMedium End With With Selection.Borders(xlEdgeBottom) .LineStyle = xlContinuous .Weight = xlMedium End With With Selection.Borders(xlEdgeRight) .LineStyle = xlContinuous .Weight = xlMedium End With Selection.Borders(xlInsideVertical).LineStyle = xlNone Selection.Borders(xlInsideHorizontal).LineStyle = xlNone End With Next ws End Sub

With the help of this macro code, you can add gridlines to all your worksheets in one go, making it much easier to keep track of all your data. Give it a try and see how quickly and easily you can design each sheet!

Change the Color of Every Other Row In One Go Sometimes, you may need to make data easier to read by changing the color of every other row. This macro code helps you do just that. Sub ChangeColor() Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets With ws .Range("A1:D50").Interior.ColorIndex = xlNone For i = 2 To 50 Step 2 .Rows(i).Interior.ColorIndex = 36 Next i End With Next ws End Sub

Create Interactive Dashboards with VBA Creating interactive dashboards can be time-consuming - unless you use this macro code! This macro code helps you create an interactive dashboard with just several clicks. Sub CreateDashboard() Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets With ws .Range("A1").Select ActiveSheet.Shapes.AddChart2(227, xlColumnClustered).Select ActiveChart.SetSourceData Source:=Range("A1:B50") End With Next ws End Sub

Hide Unused Cells with VBA Do you want to hide unused cells on your Excel worksheet? This macro code helps you do that quickly and easily. Sub HideCells() Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets With ws .Range("A1:D50").SpecialCells(xlCellTypeBlanks).Select Selection.EntireRow.Hidden = True End With Next ws End Sub

Include Sum Of Cells In The Bottom Row Would you like to include the sum of all the cells in the bottom row of any worksheet? This macro code helps you do just that. Sub SumCells() Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets With ws .Range("A1").Select Range("A51").FormulaR1C1 = "=SUM(R1C:R50C)" End With Next ws End Sub

Automatically Insert Filenames Into Cells On Any Worksheet Sometimes, you may need to insert the filename of an Excel workbook into a cell. This macro code helps you do that with just one click. Sub InsertFileName() Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets With ws .Range("A1").Select ActiveCell.FormulaR1C1 = "Filename:" & ThisWorkbook.Name End With Next ws End Sub

Add Headers and Footers to All Worksheets Do you need to add headers and footers to all worksheets in a workbook? This macro code helps you do that quickly and easily. Sub AddHeadersAndFooter() Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets With ws .PageSetup.CenterHeader = "My Header Text" .PageSetup.CenterFooter = "My Footer Text" End With Next ws End Sub

Highlight Cells with Duplicate Values Do you want to highlight cells with duplicate values? This macro code helps you do that quickly and easily. Sub HighlightDuplicates() Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets With ws .Range("A1:B50").Select Selection.FormatConditions.AddUniqueValues

Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority

With Selection.FormatConditions(1) .DupeUnique = xlDuplicate .Interior.ColorIndex = 3 End With End With Next ws End Sub

Freeze The Top Row of Any Worksheet Do you want to freeze the top row of any worksheet? This macro code helps you do that quickly and easily. Sub FreezeTopRow() Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets With ws .Range("A1").Select ActiveWindow.FreezePanes = True End With Next ws End Sub

Find All Text Strings in Any Worksheet Do you need to find all text strings in any worksheet? This macro code helps you do that quickly and easily. Sub FindTextString() Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets With ws .Range("A1:B50").Select Selection.Find(What:="My Text", After:=ActiveCell, LookIn:=xlFormulas _ , LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase _ :=False).Activate End With

Next ws End Sub

Insert a Date and Time Stamp Do you need to insert a date and time stamp into any spreadsheet? This macro code helps you do that quickly and easily. Sub InsertDateTimeStamp() Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets With ws .Range("A1").Select ActiveCell.FormulaR1C1 = Now() End With Next ws End Sub

Protect or Unprotect Any Worksheet Do you need to protect or unprotect any worksheet? This macro code helps you do that quickly and easily. Sub ProtectUnprotectSheet() Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets With ws .Protect Password:="MyPassword" 'or '.Unprotect Password:="MyPassword" End With Next ws End Sub

Insert a Hyperlink into Any Cell Do you need to insert a hyperlink into any cell? This macro code helps you do that quickly and easily. Sub InsertHyperLink() Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets With ws .Range("A1").Select ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="http://www.mysite.com" , TextToDisplay:="My Website" End With Next ws End Sub

Copy Existing Worksheets Into Another Workbook Do you need to copy existing worksheets into another workbook? This macro code helps you do that quickly and easily. Sub CopyWorksheet() Dim wbTarget As Workbook Dim wsSource As Worksheet Set wbTarget = Workbooks.Open("C:\MyWorkbooks\MyWorkbook.xls") For Each wsSource In ThisWorkbook.Sheets wsSource.Copy after:=wbTarget.Sheets(wbTarget.Sheets.Count) Next Set wbTarget = Nothing End Sub

Refresh All Pivot Tables Do you need to refresh all pivot tables? This macro code helps you do that quickly and easily. Sub RefreshPivotTables() Dim ws As Worksheet

For Each ws In ThisWorkbook.Sheets If ws.PivotTables.Count > 0 Then For Each pvt In ws.PivotTables pvt.RefreshTable Next End If Next ws End Sub

Delete All Unused Cells from All Worksheets Do you need to delete all unused cells from all worksheets? This macro code helps you do that quickly and easily. Sub DeleteUnusedCells() Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets If Not Application.Intersect(ws.UsedRange, ws.Cells) Is Nothing Then On Error Resume Next Selection.SpecialCells(xlCellTypeBlanks).Select Selection.Delete Shift:=xlUp On Error GoTo 0 End If

Next ws End Sub

Hide or Unhide Any Sheet Do you need to hide or unhide any sheet? This macro code helps you do that quickly and easily.

Sub HideUnhideSheet() Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets With ws .Visible = xlVeryHidden 'or xlSheetVisible End With Next ws End Sub

Insert a New Column in Active Sheet Do you need to insert a new column in the active sheet? This macro code helps you do that quickly and easily. Sub InsertNewColumn() Dim ws As Worksheet Set ws = ActiveSheet With ws .Columns("A:A").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove End With End Sub

Sum All Values in a Column Do you need to sum all values in a column? This macro code helps you do that quickly and easily. Sub SumColumn() Dim ws As Worksheet Set ws = ActiveSheet With ws Range("A2").FormulaR1C1 = "=SUM(RC:R" & Cells(Rows.Count, 1).End(xlUp).Row & ")" End With End Sub

Split Text into Different Cells Do you need to split text into different cells? This macro code helps you do that quickly and easily. Sub SplitText() Dim ws As Worksheet

Set ws = ActiveSheet With ws Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _ TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _ Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _ :=":", FieldInfo:=Array(1, 4)

End With End Sub

Replace Values in Multiple Columns Do you need to replace values in multiple columns? This macro code helps you do that quickly and easily. Sub ReplaceValues() Dim ws As Worksheet Set ws = ActiveSheet With ws For Each cell In Intersect(Selection, Range("A:A")) 'Change this range as needed. cell.Offset(0, 1).Value = Application.WorksheetFunction.VLookup( _ cell.Value, Sheet2!Range("A:B"), 2, False) 'Change the sheet name or ranges as needed. Next cell End With End Sub

Create Chart from Data Range Do you need to create chart from data range? This macro code helps you do that quickly and easily. Sub CreateChart() Dim ws As Worksheet Set ws = ActiveSheet With ws Charts.Add 'Add the chart according to your data range below ActiveChart.SetSourceData Source:=Range("A1:B4") 'Change the range as needed End With End Sub

Sort Data by Specified Order Do you need to sort data by specified order? This macro code helps you do that quickly and easily. Sub SortData() Dim ws As Worksheet Set ws = ActiveSheet With ws Range("A1:D30").Sort Key1:=Range("A2"), Order1:=xlAscending, _ Key2:=Range("B2"), Order2:=xlAscending 'Change the range as needed End With End Sub

Delete Blank Rows Do you need to delete blank rows? This macro code helps you do that quickly and easily. Sub DeleteBlankRows() Dim ws As Worksheet

Set ws = ActiveSheet With ws On Error Resume Next 'Skip errors For Each c In Range("A1:F100") 'Change the range as needed If c.Value = "" Then c.EntireRow.Delete End If Next c End With End Sub

Copy and Paste in a Range Do you need to copy and paste in a range? This macro code helps you do that quickly and easily. Sub CopyPasteRange() Dim ws As Worksheet Set ws = ActiveSheet With ws Range("A1:F100").Copy 'Change the range as needed Range("A2").Select 'Change this range as needed Selection.PasteSpecial xlPasteValuesAndNumberFormats 'Pastes only values and number formats, not formatting or formulas. End With End Sub

Validate Data with Data Validation List Do you need to validate data with data validation list? This macro code helps you do that quickly and easily. Sub ValidateData() Dim ws As Worksheet Set ws = ActiveSheet With ws Range("A1:A100").Select 'Change the range as needed Selection.Validation.Delete 'Deletes any existing validations in the range Selection.Validation.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Formula1:="Yes,No" 'Change the list as needed

End With End Sub

Merge Cells in a Range Do you need to merge cells in a range? This macro code helps you do that quickly and easily. Sub MergeCells() Dim ws As Worksheet Set ws = ActiveSheet With ws Range("A1:F100").Merge 'Change the range as needed Range("A1").Select 'Change this range as needed With Selection.Font .Name = "Calibri" .Size = 12 .Bold = True End With End With End Sub

Copy Entire Column Do you need to copy an entire column? This macro code helps you do that quickly and easily. Sub CopyColumn() Dim ws As Worksheet Set ws = ActiveSheet With ws Columns("A:A").Copy 'Change the range as needed Range("B1").Select 'Change this range as needed Selection.PasteSpecial xlPasteValuesAndNumberFormats 'Pastes only values and number formats, not formatting or formulas. End With End Sub

Conclusion These are just some of the most commonly used macros for Excel. With just a few clicks and some simple coding, you can make your work with spreadsheets much easier and more efficient. Try experimenting with these macros to find out how they can help you get the most out of your data! These are just some examples of macros you can use in Excel. With programming knowledge, you can customize each macro to fit specific needs or create new ones that automate complex tasks. Utilizing macros in Excel will greatly enhance your workflow and make everyday tasks much simpler.Try out these macros and watch how quickly and easily they help you work with your data! With all the essential tools at your disposal, you should now be able to confidently create powerful macros that automate everyday processes in Excel. From basic hyperlinks to more advanced automation techniques, using VBA and macros can help you turn Excel into an even more powerful tool.

Join our closed community on Telegram, where you can order or discuss any eBook: https://t.me/ebook_community