VBA Class Module to navigate Between ActiveX Controls on a Sheet by pressing TAB key

Viewed 208

Trying to Accomplish: There are a few TextBoxes and ComboBoxes (ActiveX Controls) arranged in order on an Excel worksheet (Sheet1) like a UserForm. I would like to navigate between these controls by tabbing (pressing TAB key).

Partial Success: I am able to navigate between TextBoxes using the method and codes shown below. However I have no idea how to go about it when ComboBoxes are also involved.

PLEASE NOTE: All these controls are grouped and it has to remain so.

How I was able to navigate between TextBoxes:

Inserted a Class Module by name ClsEventTxtBx and added the following codes

    Public WithEvents CTxtBx As MSForms.TextBox

    Private Sub CTxtBx_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
        If KeyCode = vbKeyTab Then
          JumpingToNextTextBox CTxtBx
        End If
    End Sub

Inserted a Standard Module and added the Subroutine JumpingToNextTextBox

    Sub JumpingToNextTextBox(ActiveCtl As MSForms.TextBox)

    Dim shp As Shape, oleshp As Shape, i As Integer, ctlArr()

    For Each shp In Sheet1.Shapes
       If shp.Type = msoGroup Then
           For Each oleshp In shp.GroupItems
               If TypeName(oleshp.OLEFormat.Object.Object) = "TextBox" Then
                  i = i + 1
                  ReDim Preserve ctlArr(1 To i)
                  ctlArr(i) = oleshp.OLEFormat.Object.Name
               End If
           Next oleshp
      End If
    Next shp

    i = 0

    For i = LBound(ctlArr) To UBound(ctlArr)
        If ActiveCtl.Name = ctlArr(i) Then
            If Not i = UBound(ctlArr) Then
                Sheet1.OLEObjects(ctlArr(i + 1)).Activate
            Else
                Sheet1.OLEObjects(ctlArr(1)).Activate
            End If
        End If
    Next I

   End Sub

Added the following codes in ThisWorkBook

    Dim ctlArr() As New ClsEventTxtBx

    Private Sub Workbook_Open()
       Dim i As Integer, shp As Shape, oleshp As Shape, oleArr(), oleObject As oleObject
       Dim oleColl As New Collection

    
       For Each shp In Sheet1.Shapes

           If shp.Type = msoGroup Then
               For Each oleshp In shp.GroupItems
                   If oleshp.Type = msoOLEControlObject Then
                       If TypeName(oleshp.OLEFormat.Object.Object) = "TextBox" Then
                           i = i + 1
                           ReDim Preserve ctlArr(1 To i)
                           Set ctlArr(i).CTxtBx = oleshp.OLEFormat.Object.Object
                       End If
                   End If
               Next oleshp
           End If

       Next shp
    End Sub
0 Answers
Related