• 512-991-7197
  • This email address is being protected from spambots. You need JavaScript enabled to view it.
  • Always Open

Welcome to Microsoft Excel Tips & Tricks

Pausing A Macro To Get A User-selected Range


Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive
 

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.


Recommend other relevant articles:

 

 

© 2015 - 2020 Austin Laptop [AustinLaptop.Com]. All Rights Reserved.