Selecting Cases in Excel

I am currently using Microsoft Excel 2003.

I would like to have a list of data, and be able to randomly choose rows out of that list.  For example:  Say i have 5000 rows of data, I would like to be able to choose 100 random samples out of that 5000.  Then be able to extract the chosen rows either manually or have VB do it for me.   I would also like to be able to easily change that number, so one sample tell it to choose 500 rows of the 5000, then the next time be able to choose 100.

I am at a lost of how to do this, or if it is even possible in Excels VB.  I had an idea of having a macro randomly choose the amount of rows i specify, then placing an X in column A, then i could sort manually and go from there.  I would be happy with that.  

Any suggestions.  Thanks for the input.
Who is Participating?
Yes, this should be possible. You will need a function to which you can pass the number of rows you want and which can return an array of the selected rows or their row numbers. (If you return the rows themselves, then you also have to pass it the name of the Excel spreadsheet, of course).

Some pseudo-ish code:

Function GetSomeRows(numRows as Integer) As Array
Dim selectedRows as Array

Dim MyValue As Integer
Randomize   ' Initialize random-number generator.

For i as Integer = 1 to numRows
     MyValue = CInt(Int((numRows * Rnd()) + 1)) ' Generate random value between 1 and numRows.
     If Array.BinarySearch(selectedRows,MyValue)=-1 Then
          i -= 1 'to make up for not adding a duplicate value
     End If

Return selectedRows

End Sub

If you want to actually pull the rows from the spreadsheet, you would have to instantiate an Excel object and build an array of the selected rows. I won't go into the details of creating the Excel object (lots of info on that here already).


Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.