Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Randomize and Sample using SQL in Excel VBA

I am using VBA for Excel and I have a workbook with a few tabs. I would like to randomize and pull a sample from each tab. An example of the code is below

   sql = "SELECT TOP " & myNum & " * " & _
   "FROM [Annual$] ORDER BY RND()"
      
   Debug.Print sql

Individually, both parts of this code works as intended. Together, however, I receive a random sample but I am no longer able to limit it. I am limited in VBA code with other options (to my understanding) but if there is a way to implement LIMIT instead of SELECT TOP then that could solve this but I don’t believe Excel is capable of this.

Here is the debug print:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT TOP 1 * FROM [Annual$] ORDER BY RND()

>Solution :

Apparently there must be some bug in the sql engine in use under the hood that adding that ORDER BY causes LIMIT to be ignored. Breaking the logic of the sql down to do the ORDER BY in a subquery and the LIMIT in the outside query appears to circumvent this bug:

SELECT TOP 1 * FROM (SELECT * FROM [Annual$] ORDER BY RND()) as sub;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading