Search code examples
excelvbaactivex

Error 91 on Frame Control upon Start Up


I have a Microsoft Form 2.0 Frame Control with three option buttons. The name of the Frame Control is Side, three option button captions are X, O, and Random with names xOption, oOption, and randomSide respectively. The code runs fine, except upon startup, if I open Excel and run the program immediately, it will give me an Error 91, note that one of the options (X, O, or Random) is already selected. In order to get rid of this error, I need to explicitly select another option, then the error goes away. I don't know why this happens. Here is the sub for the Frame Control

Public Sub Side_Click()

sideLetter = Side.ActiveControl.Caption
If StrComp(sideLetter, "Random") = 0 Then
    Randomize
    tempRand = Int((Rnd() * 2 + 1))
    If tempRand = 1 Then
        sideLetter = "X"
    Else
        sideLetter = "O"
    End If
End If
End Sub

The Line sideLetter = Side.ActiveControl.Caption Is the one causing the issue. I have not explicitly declared Side as a frame control in case that's some helpful information because I'm thinking that the object is already declared just by making the Frame Control. Thanks in advance!


Solution

  • You need to check that Side.ActiveControl is actually an object, before you read it's Caption:

    Public Sub Side_Click()
    If Not Side.ActiveControl Is Nothing Then
        sideLetter = Side.ActiveControl.Caption
        If StrComp(sideLetter, "Random") = 0 Then
            Randomize
            tempRand = Int((Rnd() * 2 + 1))
            If tempRand = 1 Then
                sideLetter = "X"
            Else
                sideLetter = "O"
            End If
        End If
    End If
    End Sub