I need a macro that will do exactly as the title says. I have 18 cells that, when a command button is pressed, it will randomly pick 6 of the 18 cells and fill them with an x. Is this even possible?
I need a macro that will do exactly as the title says. I have 18 cells that, when a command button is pressed, it will randomly pick 6 of the 18 cells and fill them with an x. Is this even possible?
can use the below
Sub Randmnumber() Range("A1:Z200").ClearContents For TM = 1 To 6 RN = Int((6 - 18 + 1) * Rnd + 18) CN = Int((6 - 18 + 1) * Rnd + 18) If RN <> 0 And CN <> 0 Then Cells(RN, CN).Value = "x" Else TM = TM - 1 End If Next End Sub
Another way:
Sub fill_random_x() Dim x As Integer, y As Integer Dim rng As Range Set rng = Sheets("Sheet1").Range("A1:C6") rng.ClearContents Do While Application.WorksheetFunction.CountIf(rng, "x") < 6 x = Application.WorksheetFunction.RandBetween(1, rng.Rows.Count) y = Application.WorksheetFunction.RandBetween(1, rng.Columns.Count) Cells(x, y) = "x" Loop End Sub
Hi, MyComputerGuy,
Your post does not comply with Rule 8 of our Forum RULES. Do not crosspost your question on multiple forums without including links here to the other threads on other forums.
Cross-posting is when you post the same question in other forums on the web. The last thing you want to do is waste people's time working on an issue you have already resolved elsewhere. We prefer that you not cross-post at all, but if you do (and it's unlikely to go unnoticed), you MUST provide a link (copy the url from the address bar in your browser) to the cross-post.
Expect cross-posted questions without a link to be closed and a message will be posted by the moderator explaining why. We are here to help so help us to help you!
Read this to understand why we ask you to do this, and then please edit your first post to include links to any and all cross-posts in any other forums (not just this site).
http://www.ozgrid.com/forum/showthread.php?t=181208
Ciao,
Holger
Use Code-Tags for showing your code: [code] Your Code here [/code]
Please mark your question Solved if there has been offered a solution that works fine for you
Sub fill_random_x_v2() Dim x As Integer, y As Integer Dim rng As Range Set rng = Sheets("Sheet1").Range("A1:C6") rng.ClearContents Do While Application.WorksheetFunction.CountIf(rng, "x") < 6 x = Int(1 + Rnd() * rng.Rows.Count) y = Int(1 + Rnd() * rng.Columns.Count) Cells(x, y) = "x" Loop End Sub
Above solution is not good.
It return wrong result on large number of results.
Here is distribution of previous solution:
And this is new solution:4,60% 5,63% 6,42% 7,03% 5,70% 4,05% 6,64% 4,45% 5,55% 4,02% 6,96% 5,65% 5,53% 6,71% 4,50% 5,65% 4,03% 6,88%
Looks like RANDEBETWEEN function doesn0t work fine5,53% 5,58% 5,59% 5,53% 5,59% 5,53% 5,56% 5,57% 5,54% 5,51% 5,55% 5,53% 5,57% 5,57% 5,58% 5,55% 5,58% 5,54%
Code is below
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks