kiến thức [Excel VBA] Lấy dữ liệu từ trang web bất kỳ

Thím có ví dụ nào về merge cell, format cell , làm việc với các ô trên google spreadsheet k share e với. CHủ yếu là e k rõ mấy cái khai bao VB. Máy cái tao tác cập nhật sửa xóa đều là do code ví dụ của bác có sẵn e làm theo.

api request với cell
Gửi thím code VBA tạo định dạng (format) cho một vùng (range), code hơi phức tạp, thím nên tham khảo tài liệu về cấu trúc JSON cụ thể thì sẽ hiểu:
Code:
Private Function GetSheetIdByName(ByVal SpreadsheetId As String, ByVal Name As String) As Long
    Dim objGoogle As GoogleOAuth2
    Set objGoogle = GetSession
    On Error Resume Next
    Dim objSpreadsheet As Spreadsheet
    Set objSpreadsheet = objGoogle.Spreadsheets.GetSpreadsheet(SpreadsheetId:=SpreadsheetId)
    On Error GoTo 0
    If Not objSpreadsheet Is Nothing Then
        Dim objSheet As Sheet
        Dim i As Long
        Dim objSheetProperties As SheetProperties
        For i = 1 To objSpreadsheet.Sheets.Count
            Set objSheet = objSpreadsheet.Sheets.Item(i)
            Set objSheetProperties = objSheet.Properties
            If objSheetProperties.Title = Name Then
                GetSheetIdByName = objSheetProperties.SheetId
                Exit For
            End If
        Next
    End If
End Function

Public Sub FormatCells()
    Dim objGoogleOAuth2 As GoogleOAuth2
    Set objGoogleOAuth2 = GetSession()
    If Not objGoogleOAuth2 Is Nothing Then
        'Khai bao bien chua yeu cau cap nhat dinh dang cua cac o (Cell)
        Dim objRepeatCellRequest As RepeatCellRequest
        Set objRepeatCellRequest = New RepeatCellRequest
        Dim lngSheetId As Long, strSpreadsheetId As String
        strSpreadsheetId = "Ma Id cua spreadsheet "
        lngSheetId = GetSheetIdByName(strSpreadsheetId, "Ten sheet")
        'Khai bao bien chua dinh nghia vung du lieu (range)
        Dim objGridRange As GridRange
        Set objGridRange = New GridRange
        'Chon cac o trong vung B3:C3
        With objGridRange
            .SheetId = lngSheetId 'Ma Id cua sheet
            .StartRowIndex = 2 'Vi tri dong dau tien, o day phai tru di 1 (do chi so bat dau tu so 0), tuc la dong bat dau la 3
            .EndRowIndex = 3 'Vi tri dong cuoi cung, khong can phai tru di 1, tuc la o ket thuc la dong so 3
            .StartColumnIndex = 1 'Vi tri cot dau tien, o day phai tru di 1 (do chi so bat dau tu so 0), tuc la cot so 2
            .EndColumnIndex = 3 'Vi tri cot cuoi cung, khong can phai tru di 1, tuc la cot ket thuc la dong so 3
            'Nhu vay, doi tuong GridRange nay dinh nghia vung du lieu co dia chi kieu A1 la: B3:C3
        End With
        'Dua vung du lieu can ap dung vao yeu cau Repeat Cell
        Set objRepeatCellRequest.Range = objGridRange
        'Khai bao bien dung cho dinh nghia dinh dang cua cac o
        Dim objUserEnteredFormat As CellFormat
        Set objUserEnteredFormat = New CellFormat
        'Khai bao bien dung cho dinh dang van ban cua cac o
        Dim objTextFormat As TextFormat
        Set objTextFormat = New TextFormat
        With objTextFormat
            .Bold = "true" 'Chu in dam
            .FontSize = 16 'Kich thuoc phong chu
            .Underline = "true" 'Duong gach duoi chan cua chu
        End With
        Set objUserEnteredFormat.TextFormat = objTextFormat
        Dim objCellData As CellData
        Set objCellData = New CellData
        Set objCellData.UserEnteredFormat = objUserEnteredFormat
        'Them yeu cau thay doi cac dinh danh cho cac o vao yeu cau Cell Data
        Set objRepeatCellRequest.Cell = objCellData
        objRepeatCellRequest.Fields = "userEnteredFormat.textFormat.bold,userEnteredFormat.textFormat.fontSize,userEnteredFormat.textFormat.underline" 'Ghi ra cu the cac truong thong tin se cap nhat
        'Chuan bi yeu cau Repeat Cell de san sang gui di
        Dim objRequests As Requests
        Set objRequests = New Requests
        Set objRequests.repeatCell = objRepeatCellRequest
        Dim objBatchUpdateSpreadsheetRequest As BatchUpdateSpreadsheetRequest
        Set objBatchUpdateSpreadsheetRequest = New BatchUpdateSpreadsheetRequest
        With objBatchUpdateSpreadsheetRequest
            .Requests.Add objRequests.ToJson
            .IncludeSpreadsheetInResponse = "false"
            .ResponseIncludeGridData = "false"
        End With
        Dim objResponse As BatchUpdateSpreadsheetResponse
        On Error Resume Next
        'Gui di yeu cau
        Set objResponse = objGoogleOAuth2.Spreadsheets.BatchUpdate.Execute(SpreadsheetId:=strSpreadsheetId, BatchUpdateSpreadsheetRequest:=objBatchUpdateSpreadsheetRequest)
        If Err.Number <> 0 Then
            MsgBox Err.Description, vbExclamation, "Error"
        End If
        On Error GoTo 0
        If Not objResponse Is Nothing Then
            Debug.Print objResponse.SpreadsheetId
        End If
    End If
End Sub
Thư viện này của mình bị một số lỗi liên quan đến phân tích JSON nên chắc phải mất khá nhiều thời gian rà soát lại nhằm đảm bảo hết lỗi.
 
Gửi thím code VBA tạo định dạng (format) cho một vùng (range), code hơi phức tạp, thím nên tham khảo tài liệu về cấu trúc JSON cụ thể thì sẽ hiểu:
Code:
Private Function GetSheetIdByName(ByVal SpreadsheetId As String, ByVal Name As String) As Long
    Dim objGoogle As GoogleOAuth2
    Set objGoogle = GetSession
    On Error Resume Next
    Dim objSpreadsheet As Spreadsheet
    Set objSpreadsheet = objGoogle.Spreadsheets.GetSpreadsheet(SpreadsheetId:=SpreadsheetId)
    On Error GoTo 0
    If Not objSpreadsheet Is Nothing Then
        Dim objSheet As Sheet
        Dim i As Long
        Dim objSheetProperties As SheetProperties
        For i = 1 To objSpreadsheet.Sheets.Count
            Set objSheet = objSpreadsheet.Sheets.Item(i)
            Set objSheetProperties = objSheet.Properties
            If objSheetProperties.Title = Name Then
                GetSheetIdByName = objSheetProperties.SheetId
                Exit For
            End If
        Next
    End If
End Function

Public Sub FormatCells()
    Dim objGoogleOAuth2 As GoogleOAuth2
    Set objGoogleOAuth2 = GetSession()
    If Not objGoogleOAuth2 Is Nothing Then
        'Khai bao bien chua yeu cau cap nhat dinh dang cua cac o (Cell)
        Dim objRepeatCellRequest As RepeatCellRequest
        Set objRepeatCellRequest = New RepeatCellRequest
        Dim lngSheetId As Long, strSpreadsheetId As String
        strSpreadsheetId = "Ma Id cua spreadsheet "
        lngSheetId = GetSheetIdByName(strSpreadsheetId, "Ten sheet")
        'Khai bao bien chua dinh nghia vung du lieu (range)
        Dim objGridRange As GridRange
        Set objGridRange = New GridRange
        'Chon cac o trong vung B3:C3
        With objGridRange
            .SheetId = lngSheetId 'Ma Id cua sheet
            .StartRowIndex = 2 'Vi tri dong dau tien, o day phai tru di 1 (do chi so bat dau tu so 0), tuc la dong bat dau la 3
            .EndRowIndex = 3 'Vi tri dong cuoi cung, khong can phai tru di 1, tuc la o ket thuc la dong so 3
            .StartColumnIndex = 1 'Vi tri cot dau tien, o day phai tru di 1 (do chi so bat dau tu so 0), tuc la cot so 2
            .EndColumnIndex = 3 'Vi tri cot cuoi cung, khong can phai tru di 1, tuc la cot ket thuc la dong so 3
            'Nhu vay, doi tuong GridRange nay dinh nghia vung du lieu co dia chi kieu A1 la: B3:C3
        End With
        'Dua vung du lieu can ap dung vao yeu cau Repeat Cell
        Set objRepeatCellRequest.Range = objGridRange
        'Khai bao bien dung cho dinh nghia dinh dang cua cac o
        Dim objUserEnteredFormat As CellFormat
        Set objUserEnteredFormat = New CellFormat
        'Khai bao bien dung cho dinh dang van ban cua cac o
        Dim objTextFormat As TextFormat
        Set objTextFormat = New TextFormat
        With objTextFormat
            .Bold = "true" 'Chu in dam
            .FontSize = 16 'Kich thuoc phong chu
            .Underline = "true" 'Duong gach duoi chan cua chu
        End With
        Set objUserEnteredFormat.TextFormat = objTextFormat
        Dim objCellData As CellData
        Set objCellData = New CellData
        Set objCellData.UserEnteredFormat = objUserEnteredFormat
        'Them yeu cau thay doi cac dinh danh cho cac o vao yeu cau Cell Data
        Set objRepeatCellRequest.Cell = objCellData
        objRepeatCellRequest.Fields = "userEnteredFormat.textFormat.bold,userEnteredFormat.textFormat.fontSize,userEnteredFormat.textFormat.underline" 'Ghi ra cu the cac truong thong tin se cap nhat
        'Chuan bi yeu cau Repeat Cell de san sang gui di
        Dim objRequests As Requests
        Set objRequests = New Requests
        Set objRequests.repeatCell = objRepeatCellRequest
        Dim objBatchUpdateSpreadsheetRequest As BatchUpdateSpreadsheetRequest
        Set objBatchUpdateSpreadsheetRequest = New BatchUpdateSpreadsheetRequest
        With objBatchUpdateSpreadsheetRequest
            .Requests.Add objRequests.ToJson
            .IncludeSpreadsheetInResponse = "false"
            .ResponseIncludeGridData = "false"
        End With
        Dim objResponse As BatchUpdateSpreadsheetResponse
        On Error Resume Next
        'Gui di yeu cau
        Set objResponse = objGoogleOAuth2.Spreadsheets.BatchUpdate.Execute(SpreadsheetId:=strSpreadsheetId, BatchUpdateSpreadsheetRequest:=objBatchUpdateSpreadsheetRequest)
        If Err.Number <> 0 Then
            MsgBox Err.Description, vbExclamation, "Error"
        End If
        On Error GoTo 0
        If Not objResponse Is Nothing Then
            Debug.Print objResponse.SpreadsheetId
        End If
    End If
End Sub
Thư viện này của mình bị một số lỗi liên quan đến phân tích JSON nên chắc phải mất khá nhiều thời gian rà soát lại nhằm đảm bảo hết lỗi.
thanks thím nhé.
 
bác thớt pro về excel quá. Tiện đây cho e hỏi vấn đề về việc lấy dữ liệu mà cần key từ web được không
Cụ thể là em hay giao dịch trên binance, muốn lấy thông tin về balance wallet và các lệnh đang mở trong Futures về Excel thì làm như nào bác.
Việc này thì em làm được bằng python rồi truyền vào excel rồi, nhưng nếu lấy trực tiếp bằng Excel thì sẽ chỉ cần 1 nút bấm, sẽ tiện hơn rất nhiều
 
bác thớt pro về excel quá. Tiện đây cho e hỏi vấn đề về việc lấy dữ liệu mà cần key từ web được không
Cụ thể là em hay giao dịch trên binance, muốn lấy thông tin về balance wallet và các lệnh đang mở trong Futures về Excel thì làm như nào bác.
Việc này thì em làm được bằng python rồi truyền vào excel rồi, nhưng nếu lấy trực tiếp bằng Excel thì sẽ chỉ cần 1 nút bấm, sẽ tiện hơn rất nhiều
Trường hợp của thím phải dùng Binance API nhé, tương tự như script Python của thím sử dụng thư viện có sẵn do Binance cung cấp, nếu đưa sang Excel VBA thì phải viết lại từ đầu đến cuối.
Thím xem tài liệu ở đây nhé:
Current All Open Orders (USER_DATA)
 
1713173878529.png

@NguyenDang95 cho e hỏi làm thế nào để cái này nó thành ege brower. Set up thế nào để nó được vậy. Nếu để webbrower như này thì e k login được. E muốn như này.
1713173964259.png
 
Trường hợp của thím phải dùng Binance API nhé, tương tự như script Python của thím sử dụng thư viện có sẵn do Binance cung cấp, nếu đưa sang Excel VBA thì phải viết lại từ đầu đến cuối.
Thím xem tài liệu ở đây nhé:
Current All Open Orders (USER_DATA)
Thanks bác đã rep. Có vẻ thực hiện trên VBA phức tạp hơn rất rất nhiều so với python :))
 
Thanks bác đã rep. Có vẻ thực hiện trên VBA phức tạp hơn rất rất nhiều so với python :))
Code Python của thím đơn giản là do Binance đã viết sẵn thư viện Python, thím chỉ cần viết vài dòng gọi đúng phương thức là ra kết quả. Còn trên Excel VBA thì không có thư viện thì phải thực hiện bằng tay, dựa vào tài liệu của Binance để làm hết các công việc như xác thực, tạo yêu cầu HTTP, xử lý JSON, v.v...
Trước cũng có một thím trên này nhờ mình xử lý bằng Excel VBA, nếu thím quan tâm thì inbox mình.
 
Thím thay cái WebBrowser Control đang có trên Form thành Edge Browser Control xem sao.
@NguyenDang95 e làm được rồi. Bác cho e hỏi e dựa vào 2 example của bác để làm thao tác với sheet và driver rồi. ( 2 file khác nhau).
GIờ e muốn trong 1 file VBA tạo 1 folder rồi tạo sheet. sau đó ghi data ra spreadsheet đó thì chỉ cần 1 cái inlucde 1 cái login thôi nhỉ.
1713321960677.png

Hiện tại đang có 2 class module này. Mà dùng trong cùng 1 source hiện e chưa làm đc. Chắc phải sửa để dùng chung 1 module để cùng tao tác với driver folder và spreasheet nhỉ.
 
@NguyenDang95 e làm được rồi. Bác cho e hỏi e dựa vào 2 example của bác để làm thao tác với sheet và driver rồi. ( 2 file khác nhau).
GIờ e muốn trong 1 file VBA tạo 1 folder rồi tạo sheet. sau đó ghi data ra spreadsheet đó thì chỉ cần 1 cái inlucde 1 cái login thôi nhỉ.
View attachment 2445824
Hiện tại đang có 2 class module này. Mà dùng trong cùng 1 source hiện e chưa làm đc. Chắc phải sửa để dùng chung 1 module để cùng tao tác với driver folder và spreasheet nhỉ.
Nếu thím muốn kết hợp các class module từ hai thư viện Google Drive API và Google Sheets API thì thím làm như sau:
1. Thêm tất cả các class module còn thiếu vào dự án của Access.
2. Chỉnh sửa nội dung của class module tên là GoogleOAuth2 như sau:
Code:
Private m_AboutResource As AboutResource
Private m_ChangesResource As ChangesResource
Private m_ChannelsResource As ChannelsResource
Private m_CommentsResource As CommentsResource
Private m_FilesResource As FilesResource
Private m_PermissionsResource As PermissionsResource
Private m_RepliesResource As RepliesResource
Private m_RevisionsResource As RevisionsResource
Private m_DrivesResource As DrivesResource

Public Property Get DrivesResource() As DrivesResource
    Set DrivesResource = m_DrivesResource
End Property

Public Property Set DrivesResource(Value As DrivesResource)
    Set m_DrivesResource = Value
End Property

Public Property Get RevisionsResource() As RevisionsResource
    Set RevisionsResource = m_RevisionsResource
End Property

Public Property Set RevisionsResource(Value As RevisionsResource)
    Set m_RevisionsResource = Value
End Property

Public Property Get RepliesResource() As RepliesResource
    Set RepliesResource = m_RepliesResource
End Property

Public Property Set RepliesResource(Value As RepliesResource)
    Set m_RepliesResource = Value
End Property

Public Property Get PermissionsResource() As PermissionsResource
    Set PermissionsResource = m_PermissionsResource
End Property

Public Property Set PermissionsResource(Value As PermissionsResource)
    Set m_PermissionsResource = Value
End Property

Public Property Get FilesResource() As FilesResource
    Set FilesResource = m_FilesResource
End Property

Public Property Set FilesResource(Value As FilesResource)
    Set m_FilesResource = Value
End Property

Public Property Get CommentsResource() As CommentsResource
    Set CommentsResource = m_CommentsResource
End Property

Public Property Set CommentsResource(Value As CommentsResource)
    Set m_CommentsResource = Value
End Property

Public Property Get ChannelsResource() As ChannelsResource
    Set ChannelsResource = m_ChannelsResource
End Property

Public Property Set ChannelsResource(Value As ChannelsResource)
    Set m_ChannelsResource = Value
End Property

Public Property Get ChangesResource() As ChangesResource
    Set ChangesResource = m_ChangesResource
End Property

Public Property Set ChangesResource(Value As ChangesResource)
    Set m_ChangesResource = Value
End Property

Public Property Get AboutResource() As AboutResource
    Set AboutResource = m_AboutResource
End Property

Public Property Set AboutResource(Value As AboutResource)
    Set m_AboutResource = Value
End Property

Public Sub AuthorizeOAuth2()
    ...
    Dim objAboutResource As AboutResource
    Set objAboutResource = New AboutResource
    objAboutResource.AccessToken = AccessToken
    Set AboutResource = objAboutResource
    Dim objChangesResource As ChangesResource
    Set objChangesResource = New ChangesResource
    objChangesResource.AccessToken = AccessToken
    Set ChangesResource = objChangesResource
    Dim objChannelsResource As ChannelsResource
    Set objChannelsResource = New ChannelsResource
    objChannelsResource.AccessToken = AccessToken
    Set ChannelsResource = objChannelsResource
    Dim objCommentsResource As CommentsResource
    Set objCommentsResource = New CommentsResource
    objCommentsResource.AccessToken = AccessToken
    Set CommentsResource = objCommentsResource
    Dim objFilesResource As FilesResource
    Set objFilesResource = New FilesResource
    objFilesResource.AccessToken = AccessToken
    Set FilesResource = objFilesResource
    Dim objPermissionsResource As PermissionsResource
    Set objPermissionsResource = New PermissionsResource
    objPermissionsResource.AccessToken = AccessToken
    Set PermissionsResource = objPermissionsResource
    Dim objRepliesResource As RepliesResource
    Set objRepliesResource = New RepliesResource
    objRepliesResource.AccessToken = AccessToken
    Set RepliesResource = objRepliesResource
    Dim objRevisionsResource As RevisionsResource
    Set objRevisionsResource = New RevisionsResource
    objRevisionsResource.AccessToken = AccessToken
    Set RevisionsResource = objRevisionsResource
    Dim objDrivesResource As DrivesResource
    Set objDrivesResource = New DrivesResource
    objDrivesResource.AccessToken = AccessToken
    Set DrivesResource = objDrivesResource
End Sub
 
Last edited:
Code của thím thiếu scope rồi, tìm xem code của thím thiếu scope nào rồi thêm vào hàm GetSession(). Khi thêm scope mới thì thím bắt buộc phải đăng xuất nhé (gọi thủ tục LogOut).
OAuth 2.0 Scopes for Google APIs
Ý thím là chỗ này hả chỗ đó e thêm để nhận cả sheet và driver rồi mà chưa đc. Vậy chắc do e chưa logout nữa.
 

Attachments

  • 1713328220137.png
    1713328220137.png
    433 KB · Views: 6
Bạn nào có ý định học vba mình khuyên nên học thẳng python cho khỏi mất thời gian.
Mình cũng mày mò vba đâu đó 2 năm. Xong tới hồi tính toán hơi nặng chút excel nó cứ treo. Chuyển qua python học vài tháng thấy một bầu trời rộng mở.
Về tính toán vba làm đc gì thì python làm đc gấp 10 lần hơn thế (cả về tốc độ lẫn tính năng)
Vể format các kiểu thì vba sao mấy thư viện excel của python cũng làm đc giống vậy
 
@NguyenDang95 bác có code nào VB mà chuyển 1 file vào 1 folder không.
E làm đang làm cái tạo 1 spreassheet của 1 folder. Mà API speadsheet nó k hỗ trợ tạo ở 1 folder nhất định nên e làm theo move vào folder nhưng biết biết code ở mục nào.
 

Attachments

  • 1713342963097.png
    1713342963097.png
    99.6 KB · Views: 6
@NguyenDang95 bác có code nào VB mà chuyển 1 file vào 1 folder không.
E làm đang làm cái tạo 1 spreassheet của 1 folder. Mà API speadsheet nó k hỗ trợ tạo ở 1 folder nhất định nên e làm theo move vào folder nhưng biết biết code ở mục nào.
Những thao tác liên quan đến tập tin trên Drive thím nên dùng Google Drive API, xem thêm ở đây:
REST Resource: files
 
Back
Top