To allow an Excel VBA range selection in your dialog box, add a RefEdit control. The following example displays a dialog box with the current region’s range address displayed in a RefEdit control. The current region is the block of nonempty cells that contains the active cell. The user can accept or change this range. When the user clicks OK, the procedure makes the range bold.
This Excel VBA example assumes the following:
- You have a UserForm named UserForm1.
- The UserForm contains a CommandButton control named OKButton.
- The UserForm contains a CommandButton control named CancelButton.
- The UserForm contains a RefEdit control named RefEdit1.
Sub BoldCells() ' Exit if worksheet is not active If TypeName(ActiveSheet) <> "Worksheet" Then Exit SubThe following procedure is executed when the OK button is clicked. This procedure does some simple error checking to make sure that the range specified in the RefEdit control is valid.' Select the current region ActiveCell.CurrentRegion.Select
' Initialize RefEdit control UserForm1.RefEdit1.Text = Selection.Address
' Show dialog UserForm1.Show End Sub
Private Sub OKButton_Click() On Error GoTo BadRange Range(RefEdit1.Text).Font.Bold = True Unload UserForm1 Exit Sub BadRange: MsgBox "The specified range is not valid." End SubIf an error occurs in Excel VBA (most likely an invalid range specification in the RefEdit control), the code jumps to the BadRange label, and a message box is displayed. The dialog box remains open so the user can select another range.
If getting a user selected range is the only function performed by your UserForm, you can simplify things by using the Application InputBox method.