Ravindra BagaleCourses & study guides

12. Macros and VBA

12.5 Sub Procedures

A macro is a Sub procedure: it starts with Sub Name() and ends with End Sub. Comments start with an apostrophe '.

Option Explicit

Sub HelloBlinkit()
    ' My first macro
    Worksheets("Report").Range("A1").Value = "Blinkit Maharashtra - Daily Report"
    Worksheets("Report").Range("A2").Value = Date
    Worksheets("Report").Range("A2").NumberFormat = "dd-mm-yyyy"
    MsgBox "Report header ready!", vbInformation, "Done"
End Sub
  • Run: put the cursor inside the Sub and press F5.
  • One Sub can call another: Call FormatHeader or just FormatHeader.
  • Private Sub hides a macro from the Macros dialog (useful for helper procedures).
  • Line continuation: end a line with a space and underscore _ to continue on the next line.

Ravindra Bagale's Tip

After running a macro, Undo (Ctrl + Z) doesn't work – many students run a wrong macro once and the data is ruined. Always test a new macro on a copy of the file (a backup). And give the Sub a meaningful name (FormatDailyReport), not Macro1.

Practice task

Write a Sub StampReport that writes "Prepared by Ravindra Bagale" in Report!A3 and the current date-time in A4 formatted dd-mm-yyyy hh:mm.