機八陽 wrote:
之前上個月還正常下載都可使用,但這個月就不行(上櫃下載不下來)
我用您的程式碼測試是正常的,您可能是查詢頻率太高,被tpex、twse擋ip
但沒聽說過tpex、twse會封鎖ip,如果您8月份10多天都不能下載
那可能是其它原因造成

另外建議,這2個網頁,不要用html格式下載,改用csv下載
上市、上櫃(html格式),大約6百萬字元
上市、上櫃(csv格式),大約1百萬字元
資料量差6倍,用csv處理會快很多
可參考200樓範例
#If VBA7 Then
Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" _
Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, _
ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
#Else
Private Declare Function URLDownloadToFile Lib "urlmon" _
Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, _
ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
#End If
Sub Get_Tpex_Twse_Csv()
Dim UrL As String, Target As String, TpexCsv As String, Clipboard As Object, Tpex As Object
Set Clipboard = CreateObject("new:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
Set Tpex = CreateObject("scripting.filesystemobject")
On Error GoTo checkid
Target = "c:\excel\" '暫存目錄,windows 10可能有權限問題,需在選項內設定信任位置,或改目錄位置
If Dir(Target, vbDirectory) = "" Then MkDir Target
'注意,暫存目錄下的檔案,會在無任何提示下刪除
If Dir(Target & "*.*") <> "" Then Kill Target & "*.*"
Sheets("工作表1").Cells.Clear
Application.DisplayAlerts = False
Application.ScreenUpdating = False
'UrL = "https://www.tpex.org.tw/web/stock/aftertrading/daily_close_quotes/stk_quote_result.php?l=zh-tw&o=csv&d=111/08/12&s=0,asc,0"
UrL = "https://www.twse.com.tw/exchangeReport/MI_INDEX?response=csv&date=20220812&type=ALLBUT0999"
URLDownloadToFile 0, UrL, Target & "temp.csv", 0, 0
'如果單純只是下載檔案,那程式碼到這裡就可以結束了
With Tpex.OpenTextFile(Target & "temp.csv", 1)
TpexCsv = Replace(Replace(.ReadAll, "=", ""), "元,", "元.")
.Close
End With
Clipboard.SetText TpexCsv
Clipboard.PutInClipboard
With Sheets("工作表1")
.Cells(1, 1).Select
.Columns(1).NumberFormat = "@"
.PasteSpecial NoHTMLFormatting:=True
.Columns("A:A").TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, Comma:=True, FieldInfo:=Array(Array(1, 2), Array(2, 1)), TrailingMinusNumbers:=True
.Columns.AutoFit
.Columns(1).ColumnWidth = 40
.Cells(1, 1).Select
End With
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Set Clipboard = Nothing
Set Tpex = Nothing
checkid:
If Err.Number <> 0 Then
Debug.Print Err.Description
End If
End Sub