VBA to open an Excel File

2019-08-01 15:30发布

I am trying to open an excel file in a folder of excel files using VBA. I direct my code to take the end user straight to the folder and allow him to choose the file from the dialog box. But I am not able to open the file even after selecting it from the dialog box.

My understanding of the problem is - I am missing out on the Command to open the file after selecting it.

Here is my Code,

thisYear = Year(Date)


'change the display name of the open file dialog
    Application.FileDialog(msoFileDialogOpen).Title = _
    "Select Input Report"

 'Remove all other filters
 Application.FileDialog(msoFileDialogOpen).Filters.Clear

 'Add a custom filter
 Call Application.FileDialog(msoFileDialogOpen).Filters.Add( _
     "Excel Files Only", "*.xls*")

     'Select the start folder
     Application.FileDialog(msoFileDialogOpen _
     ).InitialFileName = "\\driveA\Reports\" & thisYear & ""

Please kindly share your thoughts. Thanks.

1条回答
做个烂人
2楼-- · 2019-08-01 16:10

I assume that you only let selecting one file (i.e. AllowMultiSelect = False).

 Dim file As String
 Dim myWbk As Workbook     

 file = Application.FileDialog(msoFileDialogOpen).SelectedItems(1) 

 Set myWbk = Workbooks.Open(file)

First line gets the path of the selected file and then second line opens it. Add this to the end of your code.

查看更多
登录 后发表回答