Pausing a macro to get a userselected range

You can create a macro that pauses while the user specifies a range of cells. The procedure in this section describes how to do this with Excel's InputBox method.

Do not confuse Excel's InputBox method with VBA's InputBox function. Although these two functions have the same name, they are not the same.

The Sub procedure that follows 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 On Error GoTo 0

' 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 in Figure 11-6.

Figure 11-6: Use an input box to pause a macro.

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. Using On Error GoTo 0 resumes normal error handling.

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

Make sure that screen updating is not turned off. Otherwise, you won't be able to select a cell. Use the ScreenUpdating property of the Application object to control screen updating while a macro is running.

Was this article helpful?

0 0

Post a comment