Pausing a Macro to Get a User-Selected RangeIn 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.
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.
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.
|