InputBox Start/End Row Selector
Excel VBA macro example for: User inputs start/end row via InputBox. Review the generated code, explanation, steps, and safety notes.
User request
User inputs start/end row via InputBox
Generated VBA code
Option Explicit
Sub SelectRowsByInput()
Dim ws As Worksheet
Dim startRow As Long, endRow As Long
Dim userInput As String
Dim parts() As String
' Set worksheet (modify as needed)
Set ws = ThisWorkbook.Sheets("Sheet1")
' Prompt user for start and end row
userInput = InputBox("Enter start and end row (e.g., 2-10):", "Select Rows")
If userInput = "" Then Exit Sub ' Cancel
' Parse input
parts = Split(userInput, "-")
If UBound(parts) <> 1 Then
MsgBox "Invalid format. Please use 'start-end' (e.g., 5-20).", vbExclamation
Exit Sub
End If
' Validate numeric
If Not IsNumeric(parts(0)) Or Not IsNumeric(parts(1)) Then
MsgBox "Start and end must be numbers.", vbExclamation
Exit Sub
End If
startRow = CLng(parts(0))
endRow = CLng(parts(1))
' Validate range
If startRow < 1 Or endRow < startRow Or endRow > ws.Rows.Count Then
MsgBox "Invalid row range. Ensure start >= 1, end >= start, and end <= " & ws.Rows.Count, vbExclamation
Exit Sub
End If
' Select the range
ws.Rows(startRow & ":" & endRow).Select
MsgBox "Rows " & startRow & " to " & endRow & " selected.", vbInformation
End SubWhat the macro does
- Prompts user for a row range in the format 'start-end' via InputBox.
- Parses the input and validates numeric values and logical range.
- Selects the specified rows on the active worksheet.
- Includes error handling for invalid input and cancellation.
How to use it
- Open Excel and press Alt+F11 to open the VBA editor.
- Insert a new module (Insert > Module).
- Copy and paste the provided code into the module.
- Modify the worksheet name in the code (currently 'Sheet1') if needed.
- Run the macro (F5) and enter a range like '2-10' when prompted.
- The specified rows will be selected on the worksheet.