Pausing A Macro To Get A User-selected Range
This tip describes how to pause a VBA macro so the use can select a range. The trick is to use the InputBox function of the Application object.
NOTE: Do not confuse this with VBA's InputBox function. Although 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.
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.
Excel has a long history, and it continues to evolve and change. Consequently, the tips provided here do not necessarily apply to all versions of Excel.
In particular, the user interface for Excel 2007 (and later), is vastly different from its predecessors. Therefore, the menu commands listed in older tips, will not correspond to the Excel 2007 (and later) user interface.
Browse Tips by Category
Search for Tips
Needs tips? Here are two books, with nothing but tips:
Contains more than 200 useful tips and tricks for Excel 2007 | Other Excel 2007 books | Amazon link: John Walkenbach's Favorite Excel 2007 Tips & Tricks