ちょっと生きづらさを抱えた人へ、気持ちを楽にするためのお手紙です。

【VBA】テキストのHTMLをHTMLドキュメントに変換する

筆箱にカンニングペーパーを入れる係のみすくです。こんにちは。
VBA関連だけまとめたブログもあります。
筆箱VBA
参照設定

ツール > 参照設定 >
Microsoft HTML Object Library
Microsoft Scripting Runtime

Option Explicit

Sub test()
    Dim htmlDoc As htmlDocument
    Set htmlDoc = ConvertTextFileToHTML("D:\dev\ExcelVBA\fudebaco.htm")
    
    Debug.Print htmlDoc.Title
    Debug.Print htmlDoc.getElementById("menu-item-2102").innerText
    
    Set htmlDoc = Nothing
End Sub

'---------------------------------------------------------------------------------------------------
'【処 理 名】テキストファイルのHTML変換
'【処理概要】テキストのHTMLをHTMLドキュメントに変換する
'【引    数】[I]ByVal filePath As String    ファイルフルパス
'【返 却 値】HTMLドキュメント
'---------------------------------------------------------------------------------------------------
Private Function ConvertTextFileToHTML(ByVal filePath As String) As htmlDocument
    Dim htmlDoc As Object
    Dim buf As String
    
    '参照設定 > Microsoft HTML Object Library
    Set htmlDoc = New htmlDocument
    
    'テキストファイル読み込み
    buf = LoadTextFile(filePath)
    'HTMLに変換
    htmlDoc.write buf
    
    Set ConvertTextFileToHTML = htmlDoc
End Function

'---------------------------------------------------------------------------------------------------
'【処 理 名】テキストファイル読み込み
'【処理概要】テキストファイルをすべて読み込む
'【引    数】[I]ByVal filePath As String    ファイルフルパス
'【返 却 値】テキストファイル取得結果
'---------------------------------------------------------------------------------------------------
Private Function LoadTextFile(ByVal filePath As String) As String
    Dim buf As String
    '参照設定 > Microsoft Scripting Runtime
    Dim oFso As FileSystemObject
    
    Set oFso = New FileSystemObject
    With oFso.GetFile(filePath).OpenAsTextStream
        buf = .ReadAll
        .Close
    End With
    Set oFso = Nothing
    
    LoadTextFile = buf
End Function

コメントを残す

メールアドレスが公開されることはありません。

CAPTCHA