ray88’s diary

お仕事で困ったとき用の自分用の覚書

IE操作 タグの一覧表を作成する

■以下のコードは「InternetExplorer」と「HTML Object Library」を参照設定している。

Sub getTable()
    Dim ie As InternetExplorer    
    '調べたいページのURLアドレスを格納する変数
    Dim strUrl As String    
    Set ie = CreateObject("InternetExplorer.Application")
    ie.Visible = True    
   'URLアドレスを指定
    strUrl = "https://info.finance.yahoo.co.jp/ranking/?kd=3&tm=d&mk=1"    
    '指定したURLのページへ移動
    ie.navigate strUrl    
    Do While ie.Busy Or ie.readyState < READYSTATE_COMPLETE
        DoEvents
    Loop    
    'タグを調べてリスト化する
    Call MarkeList(ie)
End Sub

■タグをリスト化する部品のコード

Sub MarkeList(objIE As InternetExplorer)
'---------------------------------------------------
'機能:WEBページのTDタグとTHタグをリスト化する
'引数1:調べたいWEBページを格納したオブジェクト変数
'---------------------------------------------------    
    'タグの通し番号
    Dim n As Long
    'td,thタグの通し番号
    Dim r As Long
    'タグ格納用
    Dim Doc As HTMLDocument    
    n = 0
    r = 0    
    Sheets("Sheet1").Select
    Cells.ClearComments
    Cells.NumberFormatLocal = "G/標準"
    Set Doc = objIE.document    
    For n = 0 To Doc.all.Length - 1
        With Doc.all(n)
            If .tagName = "TD" Or .tagName = "TH" Then
                r = r + 1
                Cells(r + 1, 1) = .tagName
                Cells(r + 1, 2) = n
                Cells(r + 1, 3) = r
                Cells(r + 1, 4) = .innerText
            End If
        End With
    Next    
    Cells.EntireColumn.AutoFit
    Cells.EntireRow.AutoFit
End Sub