VBA: random result within a list of entries with a specific "tag"

cw0677

New Member
Joined
Mar 13, 2014
Messages
2
Hi, I'm a newbie to the macro world and quite illiterate.

I have an excel file where Column A is a huge list of music artists (5000 and counting) and Column B is the artist "tag", i.e. the music genre the artist plays. When I click on the macro button, I wanna get a random artist but not totally random, it's gotta be within the genre that the button is intended for. In my example (see picture below) it's a "random rock artist" button and I entered 10 different artists and 5 different genres (the rock artists are 3, so in this short example I'll have one random rock artist). The result should show on another cell, for example D7. What's the macro code I should use? Thank you!


Ta9J440.jpg
 

Excel Facts

Whats the difference between CONCAT and CONCATENATE?
The newer CONCAT function can reference a range of cells. =CONCATENATE(A1,A2,A3,A4,A5) becomes =CONCAT(A1:A5)
First, enter the following code in a regular module (Alt+F11 > Insert > Module > Copy/paste the code> Alt+Q)...

Code:
Option Explicit

Sub SelectRandomRockArtist()

    Dim vData           As Variant
    Dim aRockArtists()  As String
    Dim Cnt             As Long
    Dim i               As Long
    
    vData = Range("A2:B" & Cells(Rows.Count, "B").End(xlUp).Row)
    
    ReDim aRockArtists(1 To UBound(vData))
    
    Cnt = 0
    For i = 1 To UBound(vData)
        If UCase(vData(i, 2)) = "ROCK" Then
            Cnt = Cnt + 1
            aRockArtists(Cnt) = vData(i, 1)
        End If
    Next i
    
    ReDim Preserve aRockArtists(1 To Cnt)
    
    Randomize
    Range("D7").Value = Application.Index(aRockArtists, Int(Rnd * Cnt) + 1)
    
End Sub

Then assign the SelectRandomRockArtist macro to your button.

Hope this helps!
 
Upvote 0

Forum statistics

Threads
1,215,065
Messages
6,122,945
Members
449,095
Latest member
nmaske

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top