Search code examples
vbaexcelopenfiledialog

Open a workbook using FileDialog and manipulate it in Excel VBA


I am learning how to use Excel macros and I found this code:

Dim fd As Office.FileDialog

Set fd = Application.FileDialog(msoFileDialogFilePicker)

With fd

    .AllowMultiSelect = False
    .Title = "Please select the file to kill his non colored cells"
    .Filters.Add "Excel", "*.xls"
    .Filters.Add "All", "*.*"

    If .Show = True Then
        txtFileName = .SelectedItems(1)
    End If

End With

This code opens the FileDialog. How can I open the selected Excel file without over-writing the previously opened?


Solution

  • Thankyou Frank.i got the idea. Here is the working code.

    Option Explicit
    Private Sub CommandButton1_Click()
    
      Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
      Dim fd As Office.FileDialog
    
      Set fd = Application.FileDialog(msoFileDialogFilePicker)
    
      With fd
        .AllowMultiSelect = False
        .Title = "Please select the file."
        .Filters.Clear
        .Filters.Add "Excel 2003", "*.xls?"
    
        If .Show = True Then
          fileName = Dir(.SelectedItems(1))
    
        End If
      End With
    
      Application.ScreenUpdating = False
      Application.DisplayAlerts = False
    
      Workbooks.Open (fileName)
    
      For Each sheet In Workbooks(fileName).Worksheets
        total = Workbooks("import-sheets.xlsm").Worksheets.Count
        Workbooks(fileName).Worksheets(sheet.Name).Copy _
            after:=Workbooks("import-sheets.xlsm").Worksheets(total)
      Next sheet
    
      Workbooks(fileName).Close
    
      Application.ScreenUpdating = True
      Application.DisplayAlerts = True
    
    End Sub