- 帖子
- 184
- 主題
- 45
- 精華
- 0
- 積分
- 407
- 點名
- 0
- 作業系統
- WIN 7
- 軟體版本
- office 2010
- 閱讀權限
- 20
- 性別
- 男
- 註冊時間
- 2010-8-19
- 最後登錄
- 2025-6-26

|
- 程式我大概說明一下
- Option Explicit
- Sub GetData()
- Dim DataSheet As Worksheet, Sh As Worksheet, Msg As Boolean '定義變數
- Dim EndDate As Date, StartDate As Date, i As Integer, AR, xR As Long '定義變數
- Dim Symbol As String, Qur As String '定義變數
- Set DataSheet = Sheets("Sheet1") '設定工作表名稱
- With DataSheet
- StartDate = .[b1] '將B1欄位值讀到變數StartDate中
- EndDate = .[b2] '將B2欄位值讀到變數EndDate中
- Symbol = .[b3] '將B3欄位值讀到變數Symbol中
- .Range("D1").CurrentRegion = "" '設定D1欄位值
- End With
- '本資料自民國94年09月01日開始提供 *** 除錯 *** '以下以94/09/01為界限,判讀輸入值是否有錯
- If StartDate < #9/1/2005# Or EndDate < #9/1/2005# Or Len(Symbol) <= 3 Or StartDate > EndDate Or EndDate > Date Then
- MsgBox "數據有誤" & IIf(StartDate < #9/1/2005#, vbLf & "StartDate :日期 小於 94年09月01日 ", "") & _
- IIf(EndDate < #9/1/2005#, vbLf & "EndDate :日期 小於 94年09月01日 ", "") & _
- IIf(Len(Symbol) <= 3, vbLf & "Symbol : 股票代號 ", "") & _
- IIf(StartDate > EndDate, vbLf & "StartDate > EndDate", "") & _
- IIf(EndDate > Date, vbLf & " EndDate >" & Date, "")
- Exit Sub
- End If
- '*********************************************
- Set Sh = Sheets.Add(Sheets(1))
- DataSheet.Activate
- Do While DateSerial(Year(StartDate), Month(StartDate), 1) <= EndDate ' DO到LOOP中的程式為以輸入值去抓取網頁的資料
- Qur = "http://www.twse.com.tw/ch/trading/exchange/BWIBBU/BWIBBU.php?myear=" & Format(StartDate, "yyyy") & "&mmon=" & Format(StartDate, "m") & "&STK_NO=" & Symbol
- With Sh
- If .QueryTables.Count = 0 Then
- .QueryTables.Add "URL;" & Qur, .[A1]
- Else
- .QueryTables(1).Connection = "URL;" & Qur
- Msg = True
- End If
- With .QueryTables(1)
- .WebFormatting = xlWebFormattingNone
- .WebSelectionType = xlSpecifiedTables
- .WebDisableDateRecognition = True
- .WebTables = "8"
- .Refresh BackgroundQuery:=False
- If Application.CountA(.ResultRange) = 0 Then Msg = False
- If Msg Then
- AR = .ResultRange.Offset(2)
- Else
- AR = .ResultRange
- End If
- With DataSheet
- xR = Application.CountA(.[d:d]) + 1
- .Cells(xR, "D").Resize(UBound(AR, 1), UBound(AR, 2)) = AR
- End With
- End With
- End With
- StartDate = DateAdd("m", 1, StartDate) '這行就是能抓跨月的計算式,抓完第一個月後,變數StartDate的月份+1
- Loop
- Application.DisplayAlerts = False
- Sh.Delete
- Application.DisplayAlerts = True
- End Sub
複製代碼 分享G大的程式碼 |
|