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 FormatHeaderor justFormatHeader. Private Subhides 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.
Ravindra Bagale's Tip – मराठी
Macro run केल्यावर Undo (Ctrl + Z) चालत नाही – बरेच students एकदा चुकीचा macro चालवतात आणि data खराब होतो. नवीन macro नेहमी file ची copy (backup) करून test करा. आणि Sub चं नाव अर्थपूर्ण ठेवा (FormatDailyReport), Macro1 नको.
Ravindra Bagale's Tip – हिंदी
Macro run करने के बाद Undo (Ctrl + Z) नहीं चलता – बहुत से students एक बार गलत macro चला देते हैं और data ख़राब हो जाता है. नया macro हमेशा file की copy (backup) पर test करो. और Sub का नाम मतलब वाला रखो (FormatDailyReport), 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.