EXCEL VBA MACRO EXAMPLE

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 Sub

What 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

  1. Open Excel and press Alt+F11 to open the VBA editor.
  2. Insert a new module (Insert > Module).
  3. Copy and paste the provided code into the module.
  4. Modify the worksheet name in the code (currently 'Sheet1') if needed.
  5. Run the macro (F5) and enter a range like '2-10' when prompted.
  6. The specified rows will be selected on the worksheet.

Generate your own Excel macro