Keeping Excel users on the right path is a big job, but somebody’s got to do it! Last week we created an Excel message box in an order form, to remind users to select a customer name.
However, we don’t want the message to appear in every order form – it should only show if the customer name cell is empty. We’ll modify the code so it checks for a customer name.
Sample File: You can download the Excel order form with last week’s message macro. Enable macros when the file opens.
Clear the Customer Name Cell
To see how to refer to the customer name cell, we’ll record a test macro.
- Select any sheet in the workbook, other than the OrderForm sheet.
- Start the Macro Recorder
- Name the macro NameTest, and store it in This Workbook
- Click on the OrderForm sheet tab, to activate that sheet
- Select cell B5, where the customer name is entered
- Stop the Macro Recorder
To see the recorded macro:
- On the Ribbon, click the View tab
- Click Macros, then click View Macros
- In the list of macros, click NameTest, then click Edit.
Here’s the recorded code, with the comment lines and blank lines removed. It shows you how to refer to a sheet and cell in Excel VBA code.
We’ll remove the Select in each line, and combine the two lines into one. At the end of the line, add: .Value = “”
The revised line of code will set the value of the customer name cell to an empty string.
Run the NameTest macro, and it should clear the customer name cell.
Check For a Customer Name
We’ll add the new code to the old code, that shows the message. To check for a customer name, we’ll create an IF…THEN section in the macro, similar to what you’d do in an IF formula on the worksheet.
In English, the instructions would be: IF the customer name cell is empty, THEN show the message. In the Excel VBA code, we’ll use these three lines:
Now, when you run the CustomerMessage macro, you should see the message box only if the customer name cell is empty.
The Next Step
Next week, we’ll add code to make the macro run automatically, when someone tries to print the order form.
Previous Excel VBA articles:
- Getting Started With Excel VBA
- Excel VBA: Edit Your Recorded Macro
- Excel VBA: Switch Column Headings to Numbers
- Excel VBA: Show a Message to Users