CÔNG TY CỔ PHẦN BLUESOFTS

Hướng dẫn lập trình VBA với Google Drive, OneDrive và DropBox Upload và Download

 Bài viết hướng dẫn cách lập trình VBA để upload tập tin lên drive, download tập tin từ drive về máy tính. Các loại drive là Google Drive, OneDrive, DropBox. Trong quá trình chạy ứng dụng bạn cần đẩy các tập tin lưu lên cloud/drive hoặc tải về để làm việc, toàn bộ việc này cần được tự động hóa bởi các lệnh lập trình cùng thư viện Add-in A-Tools.

Video hướng dẫn nhanh


Hướng dẫn lập trình

Đầu tiên bạn cần:nhúng thư viện AddinATools.DLL vào VBAProject trong tập tin của bạn. Nếu bạn chưa đọc bài đầu tiên, hãy xem hướng dẫn tại bài viết này để có kiến thức hệ thống.

Tạo module để viết code. Trên đầu module hãy khai báo hằng số MyCloudType để chỉ định loại drive bạn muốn kết nối.
Private Const MyCloudType = ctGoogleDrive 
'Private Const MyCloudType = ctOneDrive
'Private Const MyCloudType = ctDropBox
Tất cả mã nguồn trong bài viết này dùng chung cho cả Google Drive, OneDrive, DropBox.

UPLOAD/TẢI TẬP TIN LÊN DRIVE

Upload tập tin lên drive

Để thực hiện việc tải dùng hàm Upload trong class BSCloudFileManager. Cấu trúc hàm Upload như sau:

Function Upload(FullName As String, PathDest, [Replace As Boolean = False], FileInfo As BSFileInfo, [ParentHandle]) As Boolean
 
+ FullName (string): là tập tin nguồn để upload lên drive.

+ PathDest (string/BSFileInfo): là kiểu string khai báo PathID (đường dẫn) trên drive để lưu tập tin. Tham số này có thể là kiểu BSFIleInfo chứa thông tin thư mục trên drive, kiểu dữ liệu thường nhận bởi hàm OpenFolderDialog() hoặc SaveFileDialog().

+ Replace (Boolean): nếu là False (ngầm định) hàm sẽ không thay thế. Nếu True hàm sẽ thay thế nếu có tập tin có trong cùng đường dẫn.

+ FileInfo (BSFileInfo): tham số này nhận thông tin của tập tin đã được upload lên drive nếu hàm Upload trả về True.

+ ParentHandle (Long/LongLong): là handle của cửa sổ cha. Có thể bỏ qua. 

Ví dụ:

Sub Drive_Upload() 
   Dim MyCloud As New BSCloud 
   Dim DestPath As BSFileInfo, FileInfo As BSFileInfo 
   Dim SourceFile As String 
   On Error GoTo lbEnd 
   If Not MyCloud.Connected(MyCloudType) Then 
      If Not MyCloud.OpenAuthor(Application, MyCloudType, Application.Hwnd) Then Exit Sub 
   End If 
   SourceFile = "C:\A-Tools\A-Tools.mdb" 
   'If MyCloud.FileManager.SaveFileDialog(Path, atUnknown, , "", , Application.Hwnd) Then
   If MyCloud.FileManager.OpenFolderDialog(DestPath, , , Application.Hwnd) Then  'Get path on drive
      MyCloud.FileManager.Upload SourceFile, DestPath, , FileInfo  'Upload to drive
      Debug.Print FileInfo.PathOrID 
      MsgBoxW FileInfo.PathOrID, VbMsgBoxStyle.vbInformation, , strUNICODE 
   End If 
lbEnd: 
   If Err <> 0 Then 
      Debug.Print "Error: " & Err.Description 
   End If 
   Set MyCloud = Nothing 
End Sub 
Ví dụ trên khi chạy sẽ hiển thị cửa sổ quản lý các folder và tập tin trên drive bởi hàm OpenFolderDialog() cho phép người dùng chọn folder để lưu tập tin, nếu hàm trả về True biến DestPath sẽ nhận thông tin đường dẫn được chọn.


Sau khi chọn nút "Select" tập tin "A-Tools.mdb" được đẩy lên Google Drive.


Nếu bạn đã xác định đường dẫn vào biến DeskPath và không cần phải mở hộp thoại để chọn thì xem ví dụ dưới đây

Sub Drive_Upload_Basic() 
   Dim MyCloud As New BSCloud 
   Dim DestPath As Variant  'Or BSFileInfo
   Dim SourceFile As String 
   Dim FileInfo As BSFileInfo 
   On Error GoTo lbEnd 
   'Check connecting
   If Not MyCloud.Connected(MyCloudType) Then 
      If Not MyCloud.OpenAuthor(Application, MyCloudType, Application.Hwnd) Then Exit Sub 
   End If 
   'Upload
   DestPath = "1PUJLVrRge5ZfOxpY8LV2-5wZnN5Fc3tY" 
   SourceFile = "C:\A-Tools\A-Tools.mdb" 
   If MyCloud.FileManager.Upload(SourceFile, DestPath, False, FileInfo) Then 
      Debug.Print FileInfo.PathOrID 
      MsgBoxW FileInfo.PathOrID, VbMsgBoxStyle.vbInformation, , strUNICODE 
   End If 
lbEnd: 
   If Err <> 0 Then 
      Debug.Print "Error: " & Err.Description 
   End If 
   Set MyCloud = Nothing 
End Sub 
Upload tập tin lên drive và thay thế

Để thay thế bạn có thể dùng hàm Upload và cần khai báo tham số Replace = True. Khai báo FileInfo.PathOrID = FileID của tập tin cần thay thế. Hoặc dùng hàm Repace(). Ví dụ như sau:

Sub Drive_Replace_Basic() 
   Dim MyCloud As New BSCloud 
   Dim DestPath As Variant  'Or BSFileInfo
   Dim SourceFile As String 
   Dim FileInfo As BSFileInfo, fi As BSFileInfo 
   On Error GoTo lbEnd 
   'Check connecting
   If Not MyCloud.Connected(MyCloudType) Then 
      If Not MyCloud.OpenAuthor(Application, MyCloudType, Application.Hwnd) Then Exit Sub 
   End If 
   'Replace - Upload(Replace := True)
   SourceFile = "C:\A-Tools\A-Tools.mdb" 
   FileInfo.PathOrID = "1gQozQR-UWUWLFspy_j5iztFXIrCn0I_0"  'FileID exists on the drive to replace
'Way 1:
   'DestPath = "1PUJLVrRge5ZfOxpY8LV2-5wZnN5Fc3tY"
   'If MyCloud.FileManager.Upload(SourceFile, DestPath, True, FileInfo) Then
'Way 2:
   If MyCloud.FileManager.Replace(FileInfo.PathOrID, SourceFile, FileInfo) Then 
      Debug.Print FileInfo.PathOrID 
      MsgBoxW FileInfo.PathOrID, VbMsgBoxStyle.vbInformation, , strUNICODE 
   End If 
   MyCloud.FileManager.GetFileInfo FileInfo.PathOrID, FileInfo 
lbEnd: 
   If Err <> 0 Then 
      Debug.Print "Error: " & Err.Description 
   End If 
   Set MyCloud = Nothing 
End Sub 

DOWNLOAD TẬP TIN TỪ DRIVE

Để download tập tin trên drive về ta dùng hàm Download() trong class BSCloudFileManager. Cấu trúc hàm như sau:

 

Function Download(FileInfo, FullName As String, [ParentHandle], [ExportFormat As String]) As Boolean   
Giải thích tham số của hàm:

+ FileInfo (String/BSFileInfo): là thông tin tập tin nguồn trên drive/cloud. Nếu khai báo kiểu BSFileInfo thì phải chứa thông tin của tập tin trên drive, thường nó nhận từ hàm OpenFileDialog(), giá trị bắt buộc là FileInfo.PathOrID. Nếu khai báo kiểu String thì nó là FileID của tập tin trên drive.

FullName (String): là đường dẫn tập tin (bao gồm cả đường dẫn folder) để lưu tập tin từ drive. Nếu để trống (FillName = ""), hàm sẽ xuất hộp thoại để người dùng chọn đường dẫn và tên tâp tin để lưu.

+ ParentHandle (Long/LongLong): là handle của cửa sổ cha. Ví dụ Application.Hwnd. Nếu bỏ qua tham số này hàm nhận handle của cửa sổ đang hoạt động.

+ ExportFormat (String): kiểu dữ liệu được xuất ra - chuyển đổi/export. Ví dụ từ xuất thành PDF, giá trị là "application/pdf". Ngầm định để trống, hàm sẽ giữ nguyên định dạng của tập tin. Bạn hãy xem thêm ví dụ về Export ở phần dưới bài viết này. 

Hàm trả về True nếu tải về thành công, trường hợp khác là False.

Ví dụ:

Sub Drive_Download() 
   Dim MyCloud As New BSCloud 
   Dim MyFile As BSFileInfo 
   Dim TargetFile As String 
   On Error GoTo lbEnd 
   If Not MyCloud.Connected(MyCloudType) Then 
      If Not MyCloud.OpenAuthor(Application, MyCloudType, Application.Hwnd) Then Exit Sub 
   End If 
   If MyCloud.FileManager.OpenFileDialog(MyFile, atUnknown, , , , Application.Hwnd) Then  'Open the file dialog to get the source file
      TargetFile = ""  'If "FullName" is empty, function Download opens the "Save" dialog box
      'for you to enter the file name and path.
      MyCloud.FileManager.Download MyFile, TargetFile, Application.Hwnd 
      Debug.Print TargetFile 
      MsgBoxW TargetFile, VbMsgBoxStyle.vbInformation, , strUNICODE 
   End If 
lbEnd: 
   If Err <> 0 Then 
      Debug.Print "Error: " & Err.Description 
   End If 
   Set MyCloud = Nothing 
End Sub 

Khi chạy thủ tục trên sẽ xuất hiện hộp thoại để chọn tập tin nguồn bởi hàm OpenFileDialog().


Sau khi nhấn nút "Open" xuất hiện cửa sổ "Save" để chọn tập tin lưu do FullName = "".


Mục "Save as type: " bạn có thể chỉ định loại định dạng mà bạn muốn xuất ra. 

Sau khi chọn "Save", nếu hàm Download() trả về True thì việc tải về đã thành công và nhận được thông báo bởi hàm MsgBox.


Download tập tin từ drive không xuất hiện hộp thoại

Nếu bạn đã có FileID của tập tin trên drive/cloud và chỉ định đường dẫn lưu tập tin thì thực hiện ví dụ sau:

Sub Drive_Download_Basic() 
   Dim MyCloud As New BSCloud 
   Dim MyFile As Variant 
   Dim TargetFile As String 
   On Error GoTo lbEnd 
   If Not MyCloud.Connected(MyCloudType) Then 
      If Not MyCloud.OpenAuthor(Application, MyCloudType, Application.Hwnd) Then Exit Sub 
   End If 
   MyFile = "1gQozQR-UWUWLFspy_j5iztFXIrCn0I_0" 
   TargetFile = "C:\Users\ADMIN\Downloads\A-Tools.mdb" 
   If MyCloud.FileManager.Download(MyFile, TargetFile, Application.Hwnd) Then 
      Debug.Print TargetFile 
      MsgBoxW TargetFile, VbMsgBoxStyle.vbInformation, , strUNICODE 
   End If 
lbEnd: 
   If Err <> 0 Then 
      Debug.Print "Error: " & Err.Description 
   End If 
   Set MyCloud = Nothing 
End Sub 


Để ý ví dụ trên bạn thấy biến MyFile bây giờ tôi khai báo kiểu String để nhận FileID thay vì BSFIleInfo ở ví du trước đó.

Xuất/Export tập tin ra các định dạng

Xuất dữ liệu chỉ thực hiện với loại cloud là Google Drive, OneDrive.


'(*) Export support for Google Drive and OneDrive only!
'Để xuất định dạng file, sử dụng tham số ExportFormat trong hàm Download()
'Giá trị của tham số ExportFormat phụ thuộc vào loại drive/cloud (CloudType).
'Nếu DriveType/CloudType là
' + OneDrive:
' ExportFormat là "PDF" nếu ddingj dạng tập tin nguồn là: csv, doc, docx, odp, ods, odt, pot, potm, potx, pps, ppsx, ppsxm, ppt, pptm, pptx, rtf, xls, xlsx
' ExportFormat là "html" nếu định dạng tập tin nguồn là: loop, fluid, wbtx
'
' + GoogleDrive:
' ExportFormat là giá trị của MIME Type. Xem thông tị tại đây: https://developers.google.com/drive/api/guides/ref-export-formats?hl=en
' Ví dụ nếu xuất ra tập tin PDF thì tham số ExportFormat là "application/pdf" 
Sub Drive_Export() 
   Dim MyCloud As New BSCloud 
   Dim MyFile As BSFileInfo 
   Dim FullName As String 
   If MyCloudType = ctDropBox Then 
      MsgBox "This drive not support Export().", vbCritical 
      Exit Sub 
   End If 
   On Error GoTo lbEnd 
   If Not MyCloud.Connected(MyCloudType) Then 
      If Not MyCloud.OpenAuthor(Application, MyCloudType, Application.Hwnd) Then Exit Sub 
   End If 
   'Get source file
   If MyCloud.FileManager.OpenFileDialog(MyFile, atUnknown, , , , Application.Hwnd) Then 
      'If "FullName" is empty, function Download opens the "Save" dialog box for you to enter the file name and path.
      'OneDrive
      If MyCloudType = ctOneDrive Then 
         MyCloud.FileManager.Download MyFile, FullName, Application.Hwnd, "pdf" 
      ElseIf MyCloudType = ctGoogleDrive Then 
         'GooogleDrive
         MyCloud.FileManager.Download MyFile, FullName, Application.Hwnd, "application/pdf" 
      End If 
      Debug.Print FullName 
      MsgBoxW FullName, VbMsgBoxStyle.vbInformation, , strUNICODE 
   End If 
lbEnd: 
   If Err <> 0 Then 
      Debug.Print "Error: " & Err.Description 
   End If 
   Set MyCloud = Nothing 
End Sub 
Xem thêm ví dụ về xuất tập ra các định dạng khác nhau từ Google Drive, OneDrive,

Bài viết tiếp theo tôi sẽ hướng dẫn các bạn cách Upload và Download nâng cao, lập trình với sự kiện để biết tiến trình đang thực hiện.

Còn tiếp...

Nếu có vướng mắc gì bạn hãy đặt câu hỏi trên group Facebook để được hỗ trợ online: https://www.facebook.com/groups/hocexcel/
Hoặc: support@bluesofts.net

Chúc các bạn thành công!
Download Add-in A-Tools để thực hành
Tác giả Nguyễn Duy Tuân