How To Select Random Rows In Excel Using Vba

To select random rows in Excel using VBA, you can use the following steps:

  1. Open the Excel file and navigate to the VBA editor by pressing ALT + F11.
  2. Insert a new module by going to Insert > Module.
  3. Within the module, define a sub procedure to select random rows:
  4. Sub SelectRandomRows()
        Dim rowNum As Long, lastRow As Long
        Dim randomNum As Integer
        
        ' Specify the range where you want to select random rows
        Dim rng As Range
        Set rng = Range("A1:A10")
        
        ' Get the last row number in the specified range
        lastRow = rng.Rows.Count
        
        ' Select a random row number between 1 and lastRow
        randomNum = Application.WorksheetFunction.RandBetween(1, lastRow)
        
        ' Select the random row in the specified range
        rng.Cells(randomNum).EntireRow.Select
    End Sub
    
  5. In the provided code, you will need to adjust the Set rng = Range("A1:A10") line to specify the range where you want to select random rows. Update the range accordingly to match your desired range.
  6. Save the VBA module and close the editor.
  7. Now, you can run the macro by going to Developer > Macros, selecting the SelectRandomRows macro, and clicking the Run button.
  8. Once executed, the macro will select a random row in the specified range.

Here’s an example to illustrate this:

Column A
Row 1
Row 2
Row 3
Row 4
Row 5

If you run the above VBA code with the specified range as Range("A1:A5"), it will randomly select one row from the range (e.g., Row 3).

Related Post

Leave a comment