Search code examples
vbams-accesstabcontrol

Deleting tabs from a TabControl with VBA /MS Access


Using this code I am trying to use my code to delete Tabs form a main "Tab", but I am missing the correct method somehow

`Private Sub DeleteAlltabs(frm As Object)

Dim tabCtrl As TabControl

    Set tabCtrl = frm.Controls("Tab")
    
    If Not tabCtrl Is Nothing Then
        For i = tabCtrl.Pages.count - 1 To 0 Step -1
            tabCtrl.Pages(i).Remove
        Next i

    End If
End Sub`

I even tried it with a while wend, and a slightly different code, but something seemingly so simple is not working:

If Not tabCtrl Is Nothing Then
        While tabCtrl.Pages.count > 0            
            tabCtrl.Pages.Remove tabCtrl.Pages(tabCtrl.Pages.count - 1)
        Wend
End If

my components are:

  1. Visual Basic for Applications
  2. Microsoft Access 16.0 Object Library
  3. OLE Automation
  4. Microsoft Office 16.0 Access Database engine Object Library

I tried both codes, and wanted it to delete the tabs, but it gave me a syntax error on both accords.


Solution

  • As Bilel explained, tabCtrl.Pages(i) refers to one Page in the tab control's Pages collection and a Page object does not have a Remove method.

    So you must use Pages.Remove instead. If you want to target a specific page based on its index, you can do this:

    tabCtrl.Pages.Remove i
    

    Or if you omit the index, the last page will be removed:

    tabCtrl.Pages.Remove
    

    I think the second version simplifies the task. Here is the code I tested:

    Public Sub DeleteAlltabs(frm As Form)
        Dim tabCtrl As TabControl
        Dim i As Long
    
        Set tabCtrl = frm.Controls("TabCtl0") ' I changed the name of the tab control
        For i = 1 To tabCtrl.Pages.Count
            tabCtrl.Pages.Remove
        Next i
    End Sub
    

    Another issue is that "You can remove a Page object from the Pages collection of a tab control only when the form is in Design view." (see Pages.Remove method)

    So I opened the form in Design View before calling the modified subroutine:

    Public Sub calling_code()
        Const cstrForm As String = "Form13"
        DoCmd.OpenForm cstrForm, acDesign
        DeleteAlltabs Forms(cstrForm)
        DoCmd.Close acForm, cstrForm, acSaveYes
    End Sub