40-Advanced-Useful-VBA-Codes-for-Excel
40-Advanced-Useful-VBA-Codes-for-Excel
So without further ado, let's dive into the world of advanced VBA codes for Excel and see what's
in store.
Table of Contents
File Export.................................................................................................................................... 2
Export Each Worksheet in a Workbook as Separate Excel Files............................................ 2
Export All Worksheets in a Workbook as Separate PDF Files................................................ 2
Export Worksheet as a PDF File Using Current Date & Time in the Filename with a Prompt.3
Export Charts from Excel to PowerPoint................................................................................. 5
Select and Export Range as PDF in Excel.............................................................................. 6
Range Manipulation.....................................................................................................................7
Select a Range to Apply Alternate Row Colors in Excel..........................................................7
Remove Blank Rows in the Active Worksheet in Excel........................................................... 7
Unhide All Rows and Columns in the Active Worksheet......................................................... 8
Unmerge All Merged Cells in Excel......................................................................................... 8
Sheet Manipulation......................................................................................................................8
Delete Multiple Sheets Without Any Warning Prompt in Excel................................................ 8
Unhide All Worksheets in Your Excel Workbook..................................................................... 9
Sort Worksheets Alphabetically in Excel............................................................................... 10
Check Whether a Specific Sheet Exists in a Workbook.........................................................11
Workbook Manipulation............................................................................................................ 11
Combine Multiple Excel Workbooks into a Single Workbook.................................................11
Delete All Blank Worksheets from an Excel Workbook......................................................... 12
Refresh All Pivot Tables in the Active Workbook................................................................... 13
Activate R1C1 Reference Style in Excel................................................................................13
Activate A1 Reference Style in Excel.................................................................................... 13
Data Manipulation......................................................................................................................14
Create a List of All Sheets [Table of Contents] in Excel.........................................................14
Transfer Data from Excel to Powerpoint................................................................................ 15
Remove All Extra Spaces from a Selected Range in Excel...................................................16
Search Value on Multiple Sheets in Excel............................................................................. 17
Formatting.................................................................................................................................. 18
AutoFit All Non-Blank Columns in the Active Worksheet in Excel......................................... 18
AutoFit All Non-Blank Rows in the Active Worksheet in Excel.............................................. 19
Highlight All the Cells Having Formulas in Excel................................................................... 19
Change Letter Case in Excel................................................................................................. 19
Highlight Cells with Wrongly Spelled Words in Excel............................................................ 20
Change Font Size of All Sheets of an Entire Workbook........................................................ 21
Remove All Text Wraps in the Active Worksheet...................................................................22
Print File..................................................................................................................................... 22
Select and Print Multiple Ranges On Separate Pages.......................................................... 22
Print Selected Sheets Using Sheet Numbers........................................................................ 23
Print Selected Sheets By Mentioning the Sheet Names........................................................23
Print the Active Worksheet with Comments...........................................................................24
Print All the Hidden As Well As Visible Worksheets.............................................................. 24
Miscellaneous............................................................................................................................ 25
Select All Non-Blanks Cells in the Active Worksheet............................................................ 25
Remove Page Breaks from the Active Worksheet.................................................................25
Count Total Number of Non-Blank Rows in a Selected Range in Excel................................ 25
Count Total Number of Non-Blank Columns in the Active WorkSheet in Excel..................... 26
Read Contents of a Selected Range Using Text To Speech................................................. 27
Search on Google from Your Excel Worksheet..................................................................... 27
Conclusion................................................................................................................................. 28
1
File Export
Sub CopySheetsToNewWorkbooks()
' Prompt the user to choose a directory to save the new sheets in
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select a folder to save the sheets in"
.Show
If .SelectedItems.Count > 0 Then
saveFolder = .SelectedItems(1) & "\"
Else
' User canceled the dialog, exit the subroutine
Exit Sub
End If
End With
Application.ScreenUpdating = False
Application.ScreenUpdating = True
End Sub
2
Sub CopySheetsToNewPDFs()
' Prompt the user to choose a directory to save the new PDFs in
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select a folder to save the PDFs in"
.Show
If .SelectedItems.Count > 0 Then
saveFolder = .SelectedItems(1) & "\"
Else
' User cancelled the dialog, exit the subroutine
Exit Sub
End If
End With
Application.ScreenUpdating = False
Application.ScreenUpdating = True
End Sub
Export Worksheet as a PDF File Using Current Date & Time in the
Filename with a Prompt
This code can export a worksheet as a pdf file. The file name will start with the sheet name
followed by the current date & time. You will get a prompt to choose a specific location to save
the pdf file. Also you will be allowed to edit the file name while saving it.
Sub SavePDFWithDateAndTime()
Dim ws As Worksheet
Dim wb As Workbook
Dim timeStr As String
Dim nameStr As String
Dim pathStr As String
3
Dim fileStr As String
Dim pathAndFileStr As String
Dim saveAsResult As Variant
Set wb = activeWorkbook
Set ws = ActiveSheet
timeStr = Format(Now(), "mm.dd.yyyy_hh.mm_AM/PM")
pathStr = wb.Path
If pathStr = "" Then
pathStr = Application.DefaultFilePath
End If
pathStr = pathStr & ""
saveAsResult = Application.GetSaveAsFilename _
(InitialFileName:=pathAndFileStr, _
FileFilter:="PDF Format (*.pdf), *.pdf", _
Title:="Choose a folder & name")
exitHandler:
Exit Sub
errorHandler:
4
MsgBox "Failed to save the PDF file."
Resume exitHandler
End Sub
Sub ExportChartToPowerPoint()
' Copy the selected chart and paste it onto the PowerPoint slide
5
ActiveChart.ChartArea.Copy
pptSlide.Shapes.Paste
Set pptShape = pptSlide.Shapes(pptSlide.Shapes.Count)
End Sub
Sub ExportRangeAsPDF()
' Define the filename and path for the exported PDF
Dim savePath As Variant
savePath = Application.GetSaveAsFilename(FileFilter:="PDF (*.pdf),
*.pdf")
6
End Sub
Range Manipulation
Sub ApplyRowColors()
End Sub
Sub RemoveBlankRows()
7
Dim i As Long
'Set the range of cells to the used range of the active worksheet
Set rng = ActiveSheet.UsedRange
End Sub
Sub UnhideAllRowsColumns()
ActiveSheet.Cells.EntireRow.Hidden = False
ActiveSheet.Cells.EntireColumn.Hidden = False
End Sub
Sub UnmergeAllCells()
ActiveSheet.Cells.UnMerge
End Sub
Sheet Manipulation
8
Sub DeleteSheetsWithNames()
' Prompt the user to enter the sheet names to delete, separated by
commas
sheetNamesToDelete = Split(InputBox("Enter the sheet names to delete,
separated by commas"), ",")
Next currentSheet
End Sub
9
Sub UnhideAllSheets()
Dim ws As Worksheet
End Sub
Sub AlphabeticallySortWorksheets()
Application.ScreenUpdating = False
Dim sheetCount As Integer, i As Integer, j As Integer
Dim sortOrder As VbMsgBoxResult
10
MsgBox "Worksheets have been sorted " & IIf(sortOrder = vbYes, "in
ascending order (A-Z).", "in descending order (Z-A).")
End Sub
Sub CheckIfSheetExists()
MsgBox "The sheet " & sheetName & " does not exist in this workbook."
End Sub
Workbook Manipulation
Sub CombineWorkbooks()
11
Dim fileDialog As fileDialog
Dim destinationWorkbook, sourceWorkbook As Workbook
Dim sourceWorksheet As Worksheet
' Open the File Dialog Box to allow the user to select multiple files
Set fileDialog = Application.fileDialog(msoFileDialogFilePicker)
fileDialog.AllowMultiSelect = True
fileCount = fileDialog.Show
' Loop through each worksheet in the source workbook and copy it to the
destination workbook
For Each sourceWorksheet In sourceWorkbook.Worksheets
sourceWorksheet.Copy
after:=destinationWorkbook.Sheets(destinationWorkbook.Worksheets.Count)
Next sourceWorksheet
End Sub
Sub DeleteBlankWorksheets()
Dim ws As Worksheet
12
For Each ws In ThisWorkbook.Worksheets
If Application.WorksheetFunction.CountA(ws.Cells) = 0 Then
ws.Delete
End If
Next ws
End Sub
Sub RefreshAllPivotTables()
Dim pt As PivotTable
End Sub
Sub ActivateR1C1ReferenceStyle()
Application.ReferenceStyle = xlR1C1
End Sub
Sub ActivateA1ReferenceStyle()
Application.ReferenceStyle = xlA1
End Sub
13
Data Manipulation
Sub CreateTableOfContents()
Dim ws As Worksheet
Dim tocSheet As Worksheet
Dim lastRow As Long
Dim sheetName As String
Dim i As Long
' Set the column headings and format the table of contents
With tocSheet
.Range("A1").Value = "List of All Sheets"
.Range("A1").Font.Bold = True
.Range("A1").Font.Size = 12
.Range("A1").HorizontalAlignment = xlCenter
.Columns("A").AutoFit
.Range("A2:A" & .Rows.Count).Font.Size = 12
End With
' Loop through all worksheets and add their names to the table of
contents
i = 2 ' Start adding sheet names in row 2
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> tocSheet.Name Then ' Exclude the table of contents
sheet
sheetName = ws.Name
14
SubAddress:="'" & sheetName & "'!A1",
TextToDisplay:=sheetName
' Move the table of contents sheet to the first position in the
workbook
tocSheet.Move Before:=ThisWorkbook.Sheets(1)
End Sub
Sub TransferDataToPowerPoint()
15
pptApp.Visible = True
Set pptPres = pptApp.Presentations.Add
Set pptSlide = pptPres.Slides.Add(1, 12)
' Cleanup
Set pptShape = Nothing
Set pptSlide = Nothing
Set pptPres = Nothing
Set pptApp = Nothing
Set xlRange = Nothing
End Sub
Sub RemoveSpaces()
'Prompt the user to select the range of cells to remove spaces from
On Error Resume Next
Set rng = Application.InputBox("Please select the range of cells to
remove spaces from:", "Select Range", Type:=8)
On Error GoTo 0
16
End If
Next cell
End Sub
Sub SearchValueOnSheets()
17
' Check if the value was found
If Not rngSearch Is Nothing Then
Set foundCell = rngSearch
Exit For
End If
Next ws
End Sub
Formatting
Sub AutoFitNonBlankColumns()
' Get the last column with data in the current worksheet
lastCol = Cells.Find("*", SearchOrder:=xlByColumns,
SearchDirection:=xlPrevious).Column
' Loop through each column and autofit if there is non-blank data
For i = 1 To lastCol
If WorksheetFunction.CountA(Columns(i)) > 1 Then
Columns(i).AutoFit
End If
Next i
End Sub
18
AutoFit All Non-Blank Rows in the Active Worksheet in Excel
This VBA code will autofit all non-blank rows in the active worksheet of an Excel workbook.
Sub AutoFitNonBlankRows()
For i = 1 To lastRow
If WorksheetFunction.CountA(Rows(i)) > 0 Then
Rows(i).EntireRow.AutoFit
End If
Next i
End Sub
Sub HighlightFormulaCells()
End Sub
Sub UpdateSelectedCellsCase()
19
' Prompt the user to input a letter to indicate the desired case
Dim caseType As String
caseType = InputBox("Enter 'a' for lowercase, 'b' for UPPERCASE, or 'c' for
Proper Case." _
& vbCrLf & vbCrLf & "Note: Only the alphabetic characters will be
affected.")
Case Else
' Display an error message and exit the subroutine
MsgBox "Invalid input. Please enter 'a', 'b', or 'c'.",
vbExclamation, "Error"
Exit Sub
End Select
End Sub
20
Sub HighlightMisspelledCells()
' Inform the user that the highlighting process has completed.
MsgBox "Misspelled cells have been highlighted.", vbInformation,
"Highlight Misspelled Cells"
End Sub
Sub ChangeFontSize()
Dim ws As Worksheet
Dim fontSize As Integer
21
End Sub
Sub RemoveTextWrap()
Cells.WrapText = False
End Sub
Print File
Sub PrintSelectedRanges()
'Declare variables
Dim numRanges As Integer
Dim currentRange As Integer
Dim rangeAddress As Object
Dim currentSheet As Worksheet
Dim printArea As Object
Dim Preview As Boolean
'Loop through each range and prompt the user to select and insert it
For currentRange = 1 To numRanges
'Prompt the user to select and insert the current range
Set printArea = Application.InputBox("Select range " & currentRange &
":", Type:=8)
22
Else
Set rangeAddress = Union(rangeAddress, printArea)
End If
Next currentRange
'Set the print area for the active sheet and print it
With ActiveSheet.PageSetup
.printArea = rangeAddress.Address
Preview = False
ActiveWindow.SelectedSheets.PrintOut Preview:=Preview
End With
End Sub
Sub PrintSelectedSheets()
End Sub
Sub PrintSheetsByName()
23
Worksheets("January").PrintOut
Worksheets("February").PrintOut
Worksheets("May").PrintOut
Worksheets("August").PrintOut
End Sub
Sub PrintSheetsWithComments()
End Sub
Sub PrintAllHiddenAndVisibleSheets()
'Declare variables
Dim currentVisible As Long
Dim workingSheet As Worksheet
24
'Print the worksheet
.PrintOut
'Restore the previous visibility state of the worksheet
.Visible = currentVisible
End With
Next workingSheet
End Sub
Miscellaneous
Sub SelectCellsWithData()
Dim ws As Worksheet
Set ws = ActiveSheet
dataRange.SpecialCells(xlCellTypeConstants).Select
End Sub
Sub DisablePageBreaks()
ActiveSheet.DisplayPageBreaks = False
End Sub
25
Count Total Number of Non-Blank Rows in a Selected Range in Excel
This subroutine counts the number of non-blank rows in the selected range. Just select a range
and then run the code. It will show the count of all non-blank rows in a popped-up dialog box.
Sub CountNonBlankRows()
rowCount = 0
Next i
End Sub
Sub CountNonBlankColumns()
26
' Loop through each column in the range
Dim col As Range
For Each col In dataRange.Columns
Next col
End Sub
Sub SpeakSelectedRange()
End Sub
27
URL by appending the q parameter (which represents the search query) to the base URL
https://www.google.com/search?q=. Finally, it opens the constructed URL in your default web
browser.
Sub GoogleSearch()
End Sub
Conclusion
I hope that this collection of 40 advanced useful VBA codes for Excel has been helpful to you
and that you're able to apply them in your daily work. Remember, these codes are just a starting
point, and there's always more to learn. Keep exploring the world of VBA and see how you can
further customize Excel to suit your needs.
Excelgraduate
Copyright 2023 excelgraduate.com | All Rights Reserved.
Web View: https://excelgraduate.com/advanced-useful-vba-codes-for-excel/
28