標題:
[原創]
Excel VBA 期交所資料自訂日數查詢
[打印本頁]
作者:
iamaraymond
時間:
2018-6-9 13:02
標題:
Excel VBA 期交所資料自訂日數查詢
本帖最後由 iamaraymond 於 2018-6-9 13:04 編輯
Excel VBA網頁資料收集教學:
http://forum.twbts.com/thread-20848-1-1.html
此程式是將上次的發文稍微改過,可以輸入想要查詢的天數
如果想固定查詢特定天數也可以直接將inputbox那一行改掉
Sub test()
Cells.Clear
Dim myXML As Object
Set myXML = CreateObject("WinHttp.WinHttpRequest.5.1")
Dim myHTML As Object
Set myHTML = CreateObject("HTMLFile")
Dim clipboard As Object
Set clipboard = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
ReDim myArr(1 To 10, 1 To 20)
dateLR = Cells(Rows.Count, "A").End(xlUp).Row
myCount = 0
myDate = Date
myNumber = InputBox("請輸入天數")
With myXML
Do
Application.Wait Now() + TimeValue("00:00:03")
myM = Format(Month(myDate), "00")
myD = Format(Day(myDate), "00")
.Open "POST", "http://www.taifex.com.tw/chinese/3/3_1_1.asp", False
.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send "qtype=2&commodity_id=TX&commodity_id2=&market_code=0&goday=&dateaddcnt=0&DATA_DATE_Y=2018&DATA_DATE_M=05&DATA_DATE_D=22&syear=2018&smonth=" & myM & "&sday=" & myD & "&datestart=2018%2F05%2F15&MarketCode=0&commodity_idt=TX&commodity_id2t=&commodity_id2t2="
myHTML.body.innerHTML = convertraw(.responseBody)
'Debug.Assert InStr(1, myText, "10368") <> 0
Set myTables = myHTML.getElementsByTagName("table")
i = 1
textRow = (myNumber - 1 - myCount) * 12 + 5
For Each myTable In myTables
If myTable.getAttribute("width") = 965 Then
' textLR = Cells(myNumber * 12, "D")
' textLR = Cells(Rows.Count, "D").End(xlUp).Row
' textLR = IIf(textLR = 1, 5, textLR + 5)
Cells(textRow, 4).Select
Cells(textRow - 1, 4) = myTable.PreviousSibling.innerText
Cells(textRow - 1, 4).WrapText = False
With clipboard
.SetText myTable.outerHTML
.PutInClipboard
End With
Sheets("工作表1").PasteSpecial NoHTMLFormatting:=False
myCount = myCount + 1
Exit For
End If
Next
myDate = myDate - 1
Loop Until myCount = CInt(myNumber)
End With
Application.StatusBar = "查詢筆數:" & myNumber & "筆"
Range("A2") = "資料範圍"
Range("A3") = Split(Split(Cells((myNumber - myCount) * 12 + 4, "D"), ":")(1), "臺")(0) & "~" & Split(Split(Cells((myNumber - 1) * 12 + 4, "D"), ":")(1), "臺")(0)
Set myXML = Nothing
End Sub
Function convertraw(rawdata)
Dim rawstr
Set rawstr = CreateObject("adodb.stream")
With rawstr
.Type = 1
.Mode = 3
.Open
.Write rawdata
.Position = 0
.Type = 2
.Charset = "UTF-8"
convertraw = .ReadText
.Close
End With
Set rawstr = Nothing
End Function
複製代碼
[attach]28807[/attach]
歡迎光臨 麻辣家族討論版版 (http://forum.twbts.com/)