0

I'm developing VBA code using Forms. I have a certain button option to let the user select the workbook using FileDialog. The workbook file may contain 4 or 5 sheets itself. I have combobox with empty.

I need to have the sheetnames of the user selected workbook listed in the combobox automaticaly without opening the workbook.

I tried with the following code, but got the names of already opened workbooks.

Private Sub CommandButton2_Click()
Set myfile = Application.FileDialog(msoFileDialogOpen)
    With myfile
    .Title = "Choose File"
    .AllowMultiSelect = False
        If .Show <> -1 Then
         Exit Sub
        End If
Fileselected = .SelectedItems(1)
    End With
With Fileselected
    For i = 1 To Sheets.Count
            ComboBox2.AddItem Sheets(i).Name
    Next i
End With

1 Answer 1

0

At the moment Sheets refers to the current workbook as you do nothing with Fileselected.

You must open the selected file, otherwise how can you examine its contents?

Set myfile = Application.FileDialog(msoFileDialogOpen)
With myfile
    .Title = "Choose File"
    .AllowMultiSelect = False
    If .Show <> -1 Then
        Exit Sub
    End If

    Fileselected = .SelectedItems(1)
End With

Dim doc As Workbook
Set doc = Application.Workbooks.Open(Fileselected)

With doc
    For i = 1 To .Sheets.Count
        ComboBox2.AddItem .Sheets(i).Name
    Next i

    .Close
End With
1
  • After.AllowMultiSelect you can add .Filters.Add "Excel Documents", "*.xls; *.xlsx; *.xlsm", 1 to filter for excel docs
    – Alex K.
    Feb 6, 2014 at 14:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.