Search code examples
excelvbauserform

Userform to navigate between severals open workbooks


I have a small program VBA which is fact a userform which allows me to display all the existing workbooks which are currently open. Via this userform I can select another workbook and by clicking the name of the workbook displays in the listbox, it reorients me to the desired Workbook by activating it. The problem is that it does not work every time and sometimes when I try to click on the desired workbook on my listbox, it does not necessarily reorient me to the desired workbook. Maybe the code related to my listbox has something wrong: With Me.ListBox1If .ListIndex <> -1 Then Workbooks (.Value).Activate If someone can help me, that would be really great.

Thanks Xavier

Please find my code below:

'code in module in VBAproject (personal.XLSB)
Sub UserFormmanagementworkbooks()
    UserForm2.Show vbModeless
End Sub

'code in userform called Userform2
Sub UserForm_Initialize()
    Dim n As Long
    Do
        n = n + 1
        Me.ListBox1.AddItem Workbooks(n).Name
    Loop Until n = Workbooks.Count
End Sub

Sub ListBox1_Click()
    With Me.ListBox1
        If .ListIndex <> -1 Then Workbooks(.Value).Activate
    End With
End Sub

Solution

  • I can think of three problems

    1. First can be a problem of initializing, i have initialized n = 0
    Sub UserForm_Initialize()
        Dim n As Long
        n = 0
        Do
            n = n + 1
            Me.ListBox1.AddItem Workbooks(n).Name
        Loop Until n = Workbooks.Count
    End Sub
    
    1. Second one is the form is taking the list of workbooks when you are opening it, so logically it will not look for any workbook opened after its initialization

    2. third problem can be the excel window. Your form will take the workbooks in one excel window, if you open two excels, it will not take excel workbooks from that. As an example take following cases.

    a. When you double click an excel file, it opens in the same window.

    b. When you click open in the already existing excel window and opens a file it will open in same window

    c. When you open another excel from the excel shortcut, you are opening another excel and any file in that excel will not be included in you form.

    My knowledge is limited to few versions of excel, maybe in other versions things are different, but in the ones i have seen these can be the cases.