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

thím chủ thớt chắc là pro excel, nếu có thời gian thím có thể xem giúp e cái này được không
E có một bảng đơn giản như dưới
1712652566473.png


E đã tạo droplist từ cột description, sau đó gắn cho một vài ô để trong bảng bên dưới. Nhưng e muốn khi lựa chọn option từ droplist thì giá trị thật của ô là type tương ứng với description (0, 1, ...) thì có khả thi không thím?

1712652702208.png
 
Mình vẫn chạy bình thường, macro trên đếm số lượng tập tin/thư mục nằm ở thư mục gốc (root) trên Google Drive của tài khoản người dùng đã đăng nhập.
1712721574327.png

Cùng 1 cái code copy sheet của bác này. E chạy trên excel 2021 thì được còn acess thì bị lỗi memory out time. ( cái lỗi bên acesss thì y hệ cái lỗi mà mình cài đặt excel 2010 phiên bản thấp hơn 2019). KHó hiểu thật. Cũng có thể do cài bản 32bit. Để e cài bản 64bit xem sao.
1712721631271.png
 
Last edited:
View attachment 2433234
Đã tạo đc spreadSheet và đọc dữ liệu như bác nói dựa vào thư viện của bác upload lên. Thanks.
Còn cái delete spreadSheet trong source thư viện thì là cái nào nhỉ.
View attachment 2433235E làm như này mà bị lỗi
Để xóa spreadsheet (tương tự như xóa tập tin trên Google Drive), thím gọi phương thức Method: files.delete của Google Drive API nhé.
Để biết được lệnh xóa đã thành công hay chưa, thím đưa phương thức nói trên vào giữa khối lệnh On Error Resume Next ... On Error GoTo 0 và kiểm tra nội dung của biến Err nhé.
 
Giờ e cần viết cái hàm copy 1 vùng của 1 sheet và paste vào 1 vùng của 1 sheet nhất định nữa là đc.
 
Giờ e cần viết cái hàm copy 1 vùng của 1 sheet và paste vào 1 vùng của 1 sheet nhất định nữa là đc.
Google Sheets API không có khái niệm copy paste nhé thím, thím phải tự xác định vùng dữ liệu cần sao chép và kích thước vùng dữ liệu cần dán dữ liệu vào.
 

Kết nối Websocket lấy dữ liệu theo thời gian thực.

Giả sử, người dùng muốn lấy dữ liệu về hoạt động giao dịch của đồng tiền số Ethereum trên trang DEX Screener tại địa chỉ: https://dexscreener.com/ethereum.
Khi truy cập và mở DevTools trên trình duyệt, người dùng có thể thấy dữ liệu được cung cấp thông qua kết nối Websocket.
1712893482835.png

1712893525968.png

Như vậy, để lấy được dữ liệu về và xử lý trong Excel, người dùng có thể thực hiện những bước sau:
1. Viết chương trình hoặc script kết nối Websocket và lưu trữ dữ liệu: Người dùng có thể chọn bất cứ ngôn ngữ lập trình nào; trong bài viết này mình chọn viết bằng PowerShell với ưu điểm là viết xong chạy ngay và không cần phải cài đặt thêm gì.
Code:
function Initialize([string]$DestinationFolder) {
    if ((Test-Path -Path $DestinationFolder) -eq $false) {
        Write-Host "Thư mục không tồn tại. Vui lòng thử lại sau!"
        return
    }
    [string]$Url = "wss://io.dexscreener.com/dex/screener/pairs/h24/1?rankBy[key]=trendingScoreH6&rankBy[order]=desc&filters[chainIds][0]=ethereum"
    [System.Threading.CancellationToken]$CT = New-Object System.Threading.CancellationToken
    [System.Net.WebSockets.ClientWebSocket]$Client = [System.Net.WebSockets.ClientWebSocket]::new()
    $Client.Options.SetRequestHeader("Origin", "https://dexscreener.com")
    $Client.Options.SetRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123.0.0.0")
    try {
        $Client.ConnectAsync($Url, $CT).GetAwaiter().GetResult()
        if ($Client.State -eq 'Open') {
            [bool]$ConnectionClosed = $false
            while ($ConnectionClosed -eq $false) {
                [byte[]]$Buffer = [byte[]] @(, 0) * 8192
                [System.ArraySegment[byte]]$BufferAS = New-Object System.ArraySegment[byte] -ArgumentList @(, $Buffer)
                [System.Net.WebSockets.WebSocketReceiveResult]$Result = $null
                [System.IO.MemoryStream]$MS = New-Object System.IO.MemoryStream
                do {
                    $Result = $Client.ReceiveAsync($BufferAS, $CT).GetAwaiter().GetResult()
                    if ($Result.MessageType -eq 'Close') {
                        $ConnectionClosed = $true
                        $Client.CloseOutputAsync([System.Net.WebSockets.WebSocketCloseStatus]::NormalClosure,[string]::Empty, $CT).GetAwaiter().GetResult()
                    }
                    else {
                        if ($Result.Count -gt 0) {
                            if ($BufferAS.Array) {
                                $MS.Write($BufferAS.Array, $BufferAS.Offset, $Result.Count)
                            }
                        }
                    }
                }
                while ($Result.EndOfMessage -eq $false)
                $MS.Seek(0, [System.IO.SeekOrigin]::Begin)
                [System.IO.StreamReader]$SR = [System.IO.StreamReader]::new($MS, [System.Text.ASCIIEncoding]::UTF8)
                [string]$Response = $SR.ReadToEnd()
                $SR.Close()
                $MS.Close()
                Write-Host $Response `r `f
                ProcessResponse -Response $Response -Client $Client -CT $CT -DestinationFolder $DestinationFolder
            }
        }
    }
    catch {
        Write-Host "Đã có lỗi xảy ra. $($_.Exception.Message)"
    }
    finally {
        if ($Client.State -eq 'Open') {
            $Client.CloseOutputAsync([System.Net.WebSockets.WebSocketCloseStatus]::NormalClosure,[string]::Empty, $CT).GetAwaiter().GetResult()
        }
    }
}

function ProcessResponse(
    [string]$Response,
    [System.Net.WebSockets.ClientWebSocket]$Client,
    [System.Threading.CancellationToken]$CT,
    [string]$DestinationFolder
) {
    if ([string]::IsNullOrEmpty($Response) -eq $false) {
        if ($Response.Contains("ping")) {
            try {
                [byte[]]$Buffer = [System.Text.ASCIIEncoding]::UTF8.GetBytes("pong")
                [System.ArraySegment[byte]]$BufferAS = New-Object System.ArraySegment[byte] -ArgumentList @(, $Buffer)
                $Client.SendAsync($BufferAS, [System.Net.WebSockets.WebSocketMessageType]::Text, $true, $CT).GetAwaiter().GetResult()
            }
            catch {
                Write-Host "Đã có lỗi xảy ra. $($_.Exception.Message)"
            }
        }
        else {
            [PSCustomObject]$Json = ConvertFrom-Json -InputObject $Response
            if (Get-Member -InputObject $Json -MemberType "Properties" -Name "type") {
                if ($Json.type -eq "pairs") {
                    $Result = @()
                    $Json.pairs | ForEach-Object {
                        $Result += New-Object psobject -Property @{
                            "chainId" = $_.chainId
                            "dexId" = $_.dexId
                            "baseTokenAddress" = $_.baseToken.address
                            "baseTokenName" = $_.baseToken.name
                            "baseTokenSymbol" = $_.baseToken.symbol
                            "quoteTokenAddress" = $_.quoteToken.address
                            "quoteTokenName" = $_.quoteToken.name
                            "quoteTokenSymbol" = $_.quoteToken.symbol
                            "price" = $_.price
                            "priceUsd" = $_.priceUsd
                            "txns_m5_buy" = $_.txns.m5.buy
                            "txns_m5_sell" = $_.txns.m5.sell
                            "txns_h1_buy" = $_.txns.h1.buy
                            "txns_h1_sell" = $_.txns.h1.sell
                            "txns_h6_buy" = $_.txns.h6.buy
                            "txns_h6_sell" = $_.txns.h6.sell
                            "txns_h24_buy" = $_.txns.h24.buy
                            "txns_h24_sell" = $_.txns.h24.sell
                            "buyers_m5" = $_.buyers.m5
                            "buyers_h1" = $_.buyers.h1
                            "buyers_h6" = $_.buyers.h6
                            "buyers_h24" = $_.buyers.h24
                            "sellers_m5" = $_.sellers.m5
                            "sellers_h1" = $_.sellers.h1
                            "sellers_h6" = $_.sellers.h6
                            "sellers_h24" = $_.sellers.h24
                            "makers_m5" = $_.makers.m5
                            "makers_h1" = $_.makers.h1
                            "makers_h6" = $_.makers.h6
                            "makers_h24" = $_.makers.h24
                            "volume_m5" = $_.volume.m5
                            "volume_h1" = $_.volume.h1
                            "volume_h6" = $_.volume.h6
                            "volume_h24" = $_.volume.h24
                            "volumeBuy_m5" = $_.volumeBuy.m5
                            "volumeBuy_h1" = $_.volumeBuy.h1
                            "volumeBuy_h6" = $_.volumeBuy.h6
                            "volumeBuy_h24" = $_.volumeBuy.h24
                            "volumeSell_m5" = $_.volumeSell.m5
                            "volumeSell_h1" = $_.volumeSell.h1
                            "volumeSell_h6" = $_.volumeSell.h6
                            "volumeSell_h24" = $_.volumeSell.h24
                            "priceChange_m5" = $_.priceChange.m5
                            "priceChange_h1" = $_.priceChange.h1
                            "priceChange_h6" = $_.priceChange.h6
                            "priceChange_h24" = $_.priceChange.h24
                            "liquidity_usd" = $_.liquidity.usd
                            "liquidity_base" = $_.liquidity.base
                            "liquidity_quote" = $_.liquidity.quote
                            "marketCap" = $_.marketCap
                            "pairCreatedAt" = $_.pairCreatedAt
                            "eti" = $_.eti
                            "c" = $_.c
                            "a" = $_.a
                        }
                    }
                    $Result | Export-Csv -Path ($DestinationFolder + "\" + (Get-Date -Format "dd-MM-yyyy hh-mm-ss") + ".csv") -NoTypeInformation -Append
                }
            }
        }
    }
}

[string]$DestinationFolder = Read-Host -Prompt "Nhập đường dẫn thư mục chứa dữ liệu sẽ lưu lại"
if ([string]::IsNullOrEmpty($DestinationFolder) -eq $false) {
    Initialize -DestinationFolder $DestinationFolder
} else {
    Write-Host "Đường dẫn thư mục không thể để trống. Vui lòng thử lại sau!"
}
Sau khi chạy script, dữ liệu sẽ tự động được lưu vào thư mục do người dùng chỉ định.
1712894270145.png

2. Từ Excel, sử dụng Power Query để nhập và làm sạch dữ liệu.
1712894749924.png

Kết quả:
1712894766982.png
 

Attachments

  • 1712894358548.png
    1712894358548.png
    455.9 KB · Views: 8
Last edited:
Back
Top