March 21, 2009

Unique Random Numbers in VBA

As mentioned in my last post, this is how I got random numbers for my new Concentration game. It uses the fact that only unique items (as far as I know) can be added to a collection. After attempting to add a new item (random integer), the code then counts the items. If continues to do this until the limit (in this case 52) is reached.

Sub GetUniqueRandomNumbers()
    Dim iAdd As Integer
    Dim iLimit As Integer
    Dim iCheck As Integer
    Dim iRnd As Integer
    Dim UniqueNumbers As New Collection

    Workbooks.Add

    iLimit = 52

    For iAdd = 1 To iLimit

StartAgain:

        iRnd = Int((iLimit - 1 + 1) * Rnd + 1)

        On Error Resume Next
        UniqueNumbers.Add iRnd, CStr(iRnd)
        On Error GoTo 0

    Next iAdd

    If UniqueNumbers.Count < iLimit Then GoTo StartAgain

    For iCheck = 1 To iLimit

        ActiveSheet.Cells(iCheck, 1).Value = UniqueNumbers.Item(iCheck)

    Next iCheck

End Sub

As promised, the Concentration game has been addded to JMT Excel Utilities, along with some other new utilities.

Export Charts As Images
This allows you to choose what charts (all of them if you want) to export in the active workbook in 3 different image formats.

Show Fonts Sheet
This shows what fonts you can use with Excel, as well as samples of how the fonts appear.

In the near future, I hope to add some more chart utilities. But for now, you can download the most recent version here.

I have also improved the code for Classic Excel Colors. It's download link is here.

Posted by andrewe at 09:51