Forum Discussion

Dharmendra_Bharwad's avatar
Dharmendra_Bharwad
Brass Contributor
Apr 20, 2021
Solved

Automation of Date

There is date appearing as 02/28/2021 in cell B6 in the attached excel sheet. I want that when the "Previous Month" button is selected, the date in cell B6 should change to 01/31/2021. Similarly when...
  • HansVogelaar's avatar
    HansVogelaar
    Apr 20, 2021

    Dharmendra_Bharwad 

    I did the following:

    • I right-clicked the Previous Month button and selected Assign Macro... from the context menu.
    • I entered PreviousMonth in the Macro name box (a macro name cannot contain spaces), then clicked New.
    • This took me to the Visual Basic Editor, with the first and last lines already created. It looked like this:
    Sub PrevMonth()
    
    End Sub
    
    • I typed the code into the line in between. It takes the value of cell B6, and used the EOMONTH function to store the last day of the previous month in B6:
    Sub PrevMonth()
        Range("B6").Value = Application.EoMonth(Range("B6").Value, -1)
    End Sub
    • I switched back to Excel, then did basically the same for the Next Month button, but with a different line of code, of course.
    • Finally, I pressed F12 from the workbook to display the Save As dialog.
    • I selected Excel Macro-enabled Workbook (*.xlsm) from the Save as type dropdown, then clicked Save.

Resources