Excel Developer Tip


Return to The Spreadsheet Page

Excel page

Tip archives

Pausing a Macro to Get a User-Selected Range

In 1-2-3, the {?} macro command pauses a macro and lets the user select a cell. Former 1-2-3 users often ask how to implement this type of behavior in Excel. The trick is to use the InputBox function of the Application object.

NOTE:
Do not confuse this with VBA's InputBox function. Althought these two functions have the same name, they are not the same.

The Sub procedure listed below demonstrates how to pause a macro and let the user select a cell.

Sub GetUserRange()
    Dim UserRange As Range
    
    Output = 565
    Prompt = "Select a cell for the output."
    Title = "Select a cell"

'   Display the Input Box
    On Error Resume Next
    Set UserRange = Application.InputBox( _
        Prompt:=Prompt, _
        Title:=Title, _
        Default:=ActiveCell.Address, _
        Type:=8) 'Range selection

'   Was the Input Box canceled?
    If UserRange Is Nothing Then
        MsgBox "Canceled."
    Else
        UserRange.Range("A1") = Output
    End If
End Sub

The input box is shown below.

inputbox.gif (1825 bytes)

Specifying a Type argument of 8 is the key to this procedure. Also, note the use of On Error Resume Next. This statement ignores the error that occurs if the user clicks the Cancel button. If so, the UserRange object variable is not defined. This example displays a message box with the text Canceled. If the user clicks OK, the macro continues.

By the way, it's not necessary to check for a valid range selection. Excel takes care of this for you.

WARNING:
Make sure ScreenUpdating is turned on. Otherwise, you won't be able to select a cell.