thầy cho em hỏi là khi mình chọn file bằng phương thức msoFileDialogFilePicker xong rồi phải dùng tiếp phương thức msoFileDialogOpen để mở file hay sao ạ? Vì nếu e chỉ dùng riêng 1 phương thức msoFileDialogOpen thì không thấy nó mở file
Khi dùng FilePicker thì file được chọn sẽ là
.SelectedItems(1) nếu chỉ chọn duy nhất 1 file
.SelectedItems(n) nếu chọn nhiều file thì sẽ xét n trong 1 vòng lặp từ 1 tới tổng số file.
Khi đó bạn có thể kết hợp thêm lệnh:
Workbooks.Open .SelectedItems(n) để mở file đó.
Bạn tham khảo code dưới đây:
Private Sub CommandButton1_Click()
' Create and set the file dialog object.
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.Filters.Clear
.Title = "Select an Excel File"
.Filters.Add "Excel Files", "*.xlsx?", 1
.AllowMultiSelect = False 'Chi chon 1 file duy nhat
Dim sFile As String 'Gan bien cho file duoc chon
If .Show = True Then
sFile = .SelectedItems(1)
End If
End With
If sFile <> "" Then
Workbooks. Open sFile ' Mo file duoc chon
End If
End Sub
trong code này, chúng ta tạo 1 biến cho fileDialogFilePicker
Sau đó thiết lập cửa sổ FilePicker chỉ hiển thị các file excel (lọc file chỉ lấy file excel), chọn 1 file duy nhất
Gán biến cho file được chọn
Sau đó mở file được chọn.