EXCEL VBA從證交所(TWSE)取得即時資訊

by 1月 15, 20200 Comments

說明

本篇是結合TWSE即時資訊APIVBA GET的應用,範例功能為每隔幾秒從證交所取得即時資訊,並儲存在EXCEL中。
這篇的GET是採同步傳輸,所以取得資料時,會有一點不順,之後會介紹非同步傳輸方式取得即時資訊。
如果想了解VBA GET/POST,參考這篇;想了解TWSE即時資訊API,參考這篇

  • 需特別留意,太頻繁從證交所抓資料,會被鎖IP。好像是每5秒超過3次,就會被鎖幾十分鐘(時間不確定),建議至少延遲2秒。
  • 範例檔下載連結在最下面,想先嘗試的朋友可先到最下面下載喔~

撰寫程式

確認worksheet名稱

名稱需與程式碼內相同,若工作表名稱不是「工作表1」,請先找到下面這行程式碼,把「工作表1」改成跟你的工作表名稱

sheetName = "工作表1"

進入VB編輯器

如果你還沒開啟開發人員頁面,請先照這篇的說明設定,若已完成設定,請進行下一步驟

匯入Module

下載以下兩個Module

將「mControl.bas」、「mTextProc.bas」拖到專案總管

貼上程式碼

  1. 在ThisWorkbook處連點滑鼠左鍵兩次
  2. 在右側貼上程式碼

程式碼如下

Option Explicit

Public Sub updateRtdTwse()
  ' Local variable declaration'
  Dim arrTmp1() As String, arrTmp2() As String
  Dim rowOffset As Long, colOffset As Long
  Dim rowCnt As Long, colCnt As Long
  Dim addrTmp As String
  Dim varTmp As Variant
  Dim sheetName As String
  Dim updateAddr As String
  Dim securityCode As String
  Dim mode As Integer

  ' Constant declaration'
  Const kPrt1StMask = 3
  Const kNoHeader = 0 ' Data array does not contain header'
  Const kNotPrtHeader = 1 ' Not print header(1st row/column)'
  Const kPrtHeader = 2 ' Print header(1st row/column)'
  Const kDirectionMask = 4
  Const kTopToBottom = 0
  Const kLiftToRight = 4

  ' Parameters'
  sheetName = "工作表1"
  updateAddr = "A1:F100"
  securityCode = "tse_2330.tw|otc_6488.tw"
  mode = kLiftToRight + kPrtHeader


  ' Get real-time data from TWSE (string array)'
  arrTmp1 = ApiRtdTwse(securityCode)

  ' Variable initialization'
  addrTmp = updateAddr
  rowOffset = Range(updateAddr).Row
  colOffset = Range(updateAddr).Column
  rowCnt = 0
  colCnt = Range(updateAddr).Columns.Count

  For Each varTmp In arrTmp1
    ' Convert a subarray (string) to a 2D array'
    arrTmp2 = Split2D(CStr(varTmp), ":", ",")

    ' Fill in missing headers'
    FillNaKey arrTmp2

    rowCnt = UBound(arrTmp2, 1) - LBound(arrTmp2, 1) + 1

    addrTmp = Range(Cells(rowOffset, colOffset), Cells(rowOffset + rowCnt - 1, colOffset + colCnt - 1)).Address

    ' Write data (2D array) to Excel worksheet'
    UpdateTable sheetName, addrTmp, arrTmp2, mode

    ' Set next row offset'
    rowOffset = rowOffset + rowCnt
  Next varTmp
End Sub

Private Sub Workbook_Open()
  With Sheets("設定")
    With .CommandButton1
      .Caption = "開始"
      .Enabled = True
      End With
    With .CommandButton2
      .Caption = "停止"
      .Enabled = False
    End With
  End With
End Sub

執行程式

  1. 將游標移到程式碼上
    (是鍵盤的游標,不是滑鼠游標)
  2. F5執行程式

執行結果

範例下載

0留言

<