Run an Excel Macro From a Cell Reference

Last week I wrote an article about hiding Excel macros, so they don’t appear in the macro list.

Collapse Dialog Button

While working on that article I noticed that the Macro dialog box has a Collapse Dialog button.

While the Macro name box is active, you can go to the workbook, select a sheet, and click on a cell.

Macro dialog box has a Collapse Dialog button
Macro dialog box has a Collapse Dialog button

Confusing Button

I couldn’t figure out why that button was there.

Even if I typed a macro name in a cell, then clicked on that cell, that macro didn’t run.

Refer to Macro Sheets

Dave Peterson suggested that the Collapse Dialog button might be related to Excel’s old style XLM macros.

And he was right – I finally found the confirmation in my old Excel 3.0 manual.

  • It says “You can also enter in the Reference box the reference of the first cell of the command macro you want to run.”

The old style macros were written on Macro sheets.

Old Excel Macro Sheets
Old Excel Macro Sheets

Starting Cell on Macro Sheet

From the Macro dialog box, you could click on the starting cell of a macro, then click the Run button.

Starting Cell on Macro Sheet
Starting Cell on Macro Sheet

Compatibility Reasons?

I guess the button is still there for compatibility with those old XLM macros. Maybe the button will eventually disappear from the Macro dialog box.

___________________

Hide an Excel Macro

When you add a macro to an Excel workbook, users can see that macro in a list when they choose Tools|Macro|Macros.

MacroListShow

Hide Your Macros

In some workbooks, you might want to hide one or more of your macros, to prevent users from running them.

Note: This technique won’t add any protection to your code, it will simply remove the macro from the list, so casual users won’t accidentally or intentionally run it.

Make the Macro Private

In this example, I have two macros – one that the users can run, and one that I’d prefer to keep hidden.

Here’s the original Excel VBA code:

MacroListCode

Revised VBA Code

If I add the word Private at the start of the Sub MySecretMacro line, that macro will NOT be included in the macro list.

MacroListPrivate

Private Macro Not in List

Now only the MyVisibleMacro appears in the list.

Private Macro Not in List
Private Macro Not in List

Run the Hidden Macro

Now that you’ve hidden the macro, so casual users won’t find it, how can you run it yourself? Here are a few ways you can run it

  • Open the Visual Basic Editor (Alt+F11), click somewhere in the macro’s code, then click the Run button.

MacroListRun

OR

  • If you know the name of the macro, type it in the Name Box, at the left of the Formula bar.
  • Press the Enter key, and the Visual Basic Editor will open automatically, with the cursor flashing in the macro’s code
  • Click the Run button.

MacroListName

OR

  • Before you hide the macro, choose Tools|Macro|Macros, select the macro, and click the Options button
  • Type a keyboard shortcut (Ctrl + Shift + M in this example) then click OK

MacroListOption

  • Close the Macro dialog box.
  • Add Private to the macro code, then use your keyboard shortcut to run it when required.

______________________

Excel Worksheet Event-Show Message Example

On my website there are sample Excel files, many of which use VBA event programming to make things happen.

What is an Event?

For Excel VBA program, an event procedure is code that runs automatically, after an “event” occurs.

An event is something that happens in an Excel workbook or worksheet. For example:

  • Type something in a cell (worksheet change event)
  • Click on a cell to select it (worksheet selection change event)
  • Click on a worksheet tab to select it (worksheet activate event)

In the Excel Visual Basic Editor, if you’re working on a Worksheet module, you can see a list of the worksheet events.

Excel VBA Worksheet Events
Excel VBA Worksheet Events

Worksheet Event Code

With event programming, it’s easy to automate your worksheets and workbooks. People don’t have to remember to click a button, or run a macro from the Macro list.

Instead, your code runs automatically when a specific event occurs. People just need to change a cell, or refresh a pivot table, and the code for that event will run.

Event Programming Example

For example, on this worksheet there’s a data validation drop down list in cell B2, where a day of the week can be selected.

data validation drop down list with weekdays
data validation drop down list with weekdays

Select a Weekday

When you select a weekday, that changes the worksheet.

If the worksheet has VBA code for the Worksheet_Change event, it will run automatically, if any cell on the worksheet is changed

In this example, the Worksheet_Change event code checks the address of the cell that was changed, to see if it was cell B2.

  • If it was cell B2, a message is displayed — “Please update the daily roster.”
  • If any other cell was changed, nothing happens

EventMessage

View the Worksheet Code

To see the code for a worksheet, right-click on its sheet tab, and click View Code.

ViewCode

The Visual Basic Editor opens, and shows the code for the active sheet.

ViewCodeMsg

Multiple Worksheet Events

What happens if you try to create multiple Worksheet_Change events on the same worksheet?

For example that message code for cell B2 works well, so you’d like to add a similar Worksheet_Change event, for a different cell.

  • If you make a change in cell B4, you’d like the date automatically entered in cell B5.

Visual Basic Error Message

Unfortunately, if you add another Worksheet_Change event, you’ll see an error message when you change a cell.

In the screen shot below, the VBA error message says:

  • Compile error: Ambiguous name detected: Worksheet_Change

That message appears if you use the same procedure name twice on the worksheet.

Compile error: Ambiguous name detected: Worksheet_Change
Compile error: Ambiguous name detected: Worksheet_Change

Combine the Event Code

Instead of creating separate events with the same name, combine both pieces of code into one.

For example, you could use Select Case, and specify what should happen when specific cells are changed.


Some situations will require a more complex solution, and if you experiment a bit, you should be able to include multiple outcomes within a single worksheet event’s code.
______________________

Is Your Excel VBA Code Clean?

Do you write Excel macro, with VBA programming? Is your code clean?

Clean Code Wristband

While I was browsing the Internet recently, I saw someone promoting a “Clean Code” wristband, with donations going to a non-profit group.

Writing clean code is an idea worth supporting, and you could snap that wristband, to wake yourself up, if your coding starts to go off track.

Green Band

Excel VBA Tutorials

If you’d like to get started with Excel VBA programming, there are several pages on my Contextures site, where you can find tutorials, sample files, and videos.

1 — How to Add Macro Code to Excel Workbook — How to copy Excel macro VBA code to your workbook, from website or sample file. Different types of code, where to paste it. Step-by-step videos, written steps

2 — Excel Macro to Save Sheets As PDF — Excel macro saves active sheet or sheets in PDF format, prompts for file name and folder. See macro code, get sample workbook with macro.

3 — How to Create Excel UserForm for Data Entry — See how to create an Excel UserForm for data entry, with text boxes and buttons. Follow step-by-step videos, detailed notes with screen shots, free Excel workbook

4 — Excel ComboBox Lists for Easy Data Entry — How to use an Excel ComboBox with a drop down list to make data entry easy in an Excel UserForm

Video: Record and Run Excel Macros

If you’re just getting started with Excel macros, this 5-minute video shows you the basic steps.

There are written steps, and an Excel workbook to download, on the Record and Test an Excel Macro page, on my Contextures site.

_______________________

Macro Creates Excel Workbooks For Entire Year

Roger Govier has created an Excel file with a macro that will set up a year’s worth of workbooks for you, at the click of a button.

It might not be the ideal workbook setup, but some people need to set these up, and this macro will certainly make the task easier.

Macro Creates Monthly Workbooks

This macro will create a series of 12 workbooks in the same folder as this workbook is stored.

You’ll be prompted to enter the year number at the beginning of the macro.

Each new workbook will be named with month and year e.g. Jan 2009.xls through Dec 2009.xls

Daily Sheets Each Month

Within each workbook, there will be a sheet for each day of the month.

There’s an option to display the numbers as ordinals, so if you click Yes for that, the sheet names would be Jan 1st, Jan 2nd and so on.

Monthly Workbook with Daily Sheets
Monthly Workbook with Daily Sheets

Get the Sample File

To download the Excel file, and to see the written steps, you can go to the Create Workbooks and Worksheets page on my Contextures site.

The zipped file contains a macro, so be sure to unblock them in Windows Explorer, before you open them.

After you open the file, enable macros, when the security message appears.

_________________________

Entering Dates and Times in Excel

In yesterday’s post I showed formulas you can use to pull information from a date in Excel.

In some workbooks you’ll enter dates manually, but often you’d like a date to be calculated automatically.

Calculate the Current Date

To show the current date in a cell, use the TODAY function:

  • =TODAY()

This date will update automatically when you open the workbook on a different date.

Calculate Current Date and Time

To show the current date and time in a cell, use the NOW function:

  • =NOW()

This formula result will update automatically, when the workbook recalculates.

Manually Enter Current Date and Time

Instead of formulas, you can enter the date and time as values. These will NOT update automatically.

  • To enter the current date in a cell as a value, press the Ctrl key and type a semi-colon (Ctrl+;)
  • To enter the current time in a cell as a value, press the Ctrl key and type a colon (Ctrl+Shift+;)

To enter date and time as value, in the same cells:

  • Enter the date (Ctrl+;)
  • Then type a space character
  • Then enter the time (Ctrl+Shift+;)

Determine When Workbook Was Last Saved

In yesterday’s post on dates, Mariusz asked how to find the date that the workbook was last saved.

Unlike Word, excel doesn’t have a menu command that will insert the last saved date.

However, you can use a bit of programming to insert the date, assuming the workbook has been saved. There is sample code in the next section.

  • Note: You could also create a User Defined Function (UDF) to calculate the date. However, I find that UDFs can slow down a workbook, so avoid them, if possible.

Macro VBA Code – Last Saved Date

Here is the code that inserts the workbook’s last saved date. It’s entered on a sheet named Data Entry, in cell A1.

Tip: You could add an event procedure in your workbook, so this code runs automatically, any time the workbook is saved.

Sub GetLastSavedDate()
On Error Resume Next
Dim sSaveDate As String
sSaveDate = FileDateTime(ActiveWorkbook.FullName)
If sSaveDate = “” Then
MsgBox “Could not determine save date.”
Else
Worksheets(“DataEntry”).Range(“A1”).Value _
= “Last Saved: ” & sSaveDate
End If
End Sub

Send Excel Data to Access

While working on client projects, I enter all my timesheet data in Excel. Why do I use Excel? Here are my top reasons (excuses):

  1. Excel is usually open on my computer, so it’s the easiest program for me to use
  2. That’s the way I’ve always done it
  3. Other important, and perfect valid, reasons that are long forgotten.

Continue reading “Send Excel Data to Access”

Add Red X Icon to Excel Message – Critical Warning

Last week a client mentioned that he uses lots of message boxes in his Excel code, and finds that users just click OK when a message appears.

Most of the messages are informational, and users have read them before, so a quick click is fine.

Critical Messages in Excel

However, some of those messages are critical, and only appear when an important decision has to be made.

Because the users are so accustomed to seeing messages, they just click OK, without reading. That could cause problems!

For example, the Excel message shown below says:

  • “Click OK to reformat your hard drive”

Busy office worker, clicking the OK button: “Sure, why not!”

Critical Excel Message with No Icon
Critical Excel Message with No Icon

Add Icon to Excel Message

I suggested that he add an icon to the critical messages, so they stand out from the rest.

Here’s the current code for this message.

Excel VBA Message Code Revised

To add a warning icon to the message, follow these steps:

  • First, in the VBA message code, type a plus sign after vbOKCancel
  • Next, in the drop down list of settings, select vbCritical
  • Then, click the Save button, to save the code changes
Add vbCritical setting in VBA code
Add vbCritical setting in VBA code

Excel Message With Red X Icon

Now when the macro runs, the critical icon (red X) appears in the message.

That won’t force anyone to read the message, but the red X might catch their attention, and make them more likely to read it.

Critical Excel message with red X icon
Critical Excel message with red X icon

Generate Numbers for Excel Testing

When answering newsgroup Excel questions, or doing testing for client projects, I often create a quick table, with a few rows and columns.

The headings, such as a list of months or weekdays can be generated by using AutoFill. That just leaves the body of the table, where I want some numbers for the test.

Create Random Numbers

I used to calculate numbers with a RAND or RANDBETWEEN formula, then copy and paste the results as values.

But that’s a lot of steps when you’re in a hurry, so I built my own number generator, that runs with a click or two.

The values aren’t important, I just want something to populate a table, pivot table or quick chart.

Excel Macros for Random Numbers

I wrote macros to generate numbers in different ranges, and added these to a toolbar menu.

You could add toolbar buttons, or assign shortcut keys to run them. In Excel 2007, add them to the Quick Access Toolbar.

Excel Macros for Random Numbers
Excel Macros for Random Numbers

Excel VBA Code

My macro code is shown below. Do you have a different way to create dummy numbers for testing?

'====================================
Sub SRandRange()
Dim c As Range
Dim x As Long, y As Long
Application.EnableEvents = False
Application.ScreenUpdating = False
x = Application.InputBox("Start Number")
y = Application.InputBox("End Number")
For Each c In Selection
c.Value = randbetween(x, y)
Next
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
'====================================
Sub SRand10()
Dim c As Range
Application.EnableEvents = False
Application.ScreenUpdating = False
For Each c In Selection
c.Value = Evaluate("=ROUND(RAND()*10,0)")
Next c
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
'====================================