Copy and paste any of the snippets above into the module window.
One of the most common uses for VBA is cleaning up messy data imports. This script automatically formats headers, adjusts column widths, and applies borders. excel vba sample code download
Press F5 to run the code or assign it to a button on your spreadsheet. Copy and paste any of the snippets above
Mastering Excel VBA (Visual Basic for Applications) is the fastest way to transform Microsoft Excel from a simple spreadsheet tool into a powerful automated engine. Whether you are looking to automate repetitive tasks, generate complex reports, or create custom functions, having access to reliable sample code is the best way to learn. Press F5 to run the code or assign
This advanced snippet allows you to trigger an email notification directly from your spreadsheet. Note: This requires the Microsoft Outlook Object Library enabled in References.
Sub CleanAndFormat() Dim ws As Worksheet Set ws = ActiveSheet With ws ' Find the last row and column Dim LastRow As Long, LastCol As Long LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column ' Format Header Row With .Range(.Cells(1, 1), .Cells(1, LastCol)) .Font.Bold = True .Interior.Color = RGB(0, 102, 204) .Font.Color = RGB(255, 255, 255) .HorizontalAlignment = xlCenter End With ' AutoFit Columns and add borders .Range(.Cells(1, 1), .Cells(LastRow, LastCol)).Columns.AutoFit .Range(.Cells(1, 1), .Cells(LastRow, LastCol)).Borders.LineStyle = xlContinuous End With MsgBox "Formatting Complete!", vbInformation End Sub Use code with caution. 2. Dynamic PDF Report Generator
Sub ExportAsPDF() Dim FileName As String Dim FolderPath As String ' Set your file path and name FolderPath = Environ("USERPROFILE") & "\Desktop\" FileName = "Report_" & Format(Now, "yyyy-mm-dd_hhmm") On Error Resume Next ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _ Filename:=FolderPath & FileName & ".pdf", _ Quality:=xlQualityStandard, _ IncludeDocProperties:=True, _ IgnorePrintAreas:=False, _ OpenAfterPublish:=True If Err.Number = 0 Then MsgBox "PDF saved to Desktop!", vbInformation Else MsgBox "Error: Could not save PDF.", vbCritical End If End Sub Use code with caution. 3. Loop Through All Worksheets