東証から銘柄データを取得するマクロ
無料のサイトから上場銘柄情報を取得すると 「突然閉鎖したとき、えらく混乱する」との経験を踏まえ、銘柄情報は以下のサイト(東証)のEXCELファイルから取得することに変更した。
http://www.jpx.co.jp/markets/statistics-equities/misc/01.html
以下は、銘柄一覧のEXCELファイルのあるサイト
http://www.jpx.co.jp/markets/statistics-equities/misc/tvdivq0000001vg2-att/data_j.xls
以下のマクロを実行すると、上記ファイルが、自分のPCの以下のフォルダーにダウンロドする。
C:\users\public\Downloads\data_j.xls
そして、今、自身が開いている、EXCELのシートにそのデータが反映される。
ただし、東証のデータは、月1回の更新につき、更新後の新規上場、上場廃止データを反映するため、それは別途、処理する必要がある。
私の場合、楽天証券のツールを使っているので、楽天証券で扱えない銘柄も反映する必要がある。
*以下は標準モジュール内で使用しないとコンパイルエラーとなる。
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
Sub 上場銘柄データの取得()
Cells.Select
Selection.ClearContents
Selection.NumberFormatLocal = "@"
Range("A1").Select
Lngret = URLDownloadToFile(0, "http://www.jpx.co.jp/markets/statistics-equities/misc/tvdivq0000001vg2-att/data_j.xls", "C:\users\public\Downloads\data_j.xls", 0, 0)
If Lngret <> 0 Then
Stop: 'サイトからデータ取得できないとき、マクロがストップする。
End If
For i = 1 To 10000
For j = 1 To 10
y = ExecuteExcel4Macro("'C:\users\public\Downloads\[data_j.xls]Sheet1'!R" & i & "c" & j)
If y = "0" Then Exit For
Cells(i, j) = y
Next
If y = "0" Then Exit For
Next
End Sub