かつてはVBAでWebデータを取得する際にInternet Explorer(IE)を使うのが定番でした。
しかし、2022年にIEのサポートが終了したことで、VBAコードもEdge対応が求められるようになっています。
本記事では、IEベースの従来コードから脱却し、Microsoft Edge(Chromium版)対応のWeb操作・データ取得手法を紹介します。
Edge WebView2対応の「SeleniumBasic + EdgeDriver」を使って、HTML要素の取得・テキスト抽出などを実行する方法を解説します。
1. 従来のIE版VBAとその問題点
IE版の基本構文(※現在は非推奨)
Dim ie As Object
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
ie.Navigate "https://example.com"
Do While ie.Busy Or ie.ReadyState <> 4
DoEvents
Loop
Dim html As Object
Set html = ie.document
MsgBox html.getElementById("price").innerText
→ IEの終了により動作しない or 不安定になるケースが増えています。
2. Edge対応の方法と準備(Selenium環境)
使用ツール:
- SeleniumBasic(VBA用Selenium)
- Microsoft Edge (Chromium)
- EdgeDriver.exe
手順:
① SeleniumBasicのインストール(GitHubから入手)
② EdgeDriverのダウンロード(Chromium版)
③ EdgeDriver.exeを C:\Program Files\SeleniumBasic
に配置(SeleniumBasicと同じフォルダ)
これでVBAからEdge(Chromium)を操作できる準備が整います。
3. VBAでEdgeを起動してWeb操作する基本コード
Sub OpenEdgeAndNavigate()
Dim driver As New WebDriver
driver.Start "edge", "https://example.com"
driver.Get "/"
MsgBox "ページタイトル:" & driver.Title
End Sub
ポイント:
"edge"
を指定することでEdgeが起動Get "/"
でルートページを読み込む(URL直書きでもOK)
4. HTMLから特定データを取得する方法
HTML要素をCSSセレクタやIDで取得し、テキストを抜き出します。
Sub GetElementText()
Dim driver As New WebDriver
driver.Start "edge", "https://example.com"
driver.Get "/"
Dim element As WebElement
Set element = driver.FindElementById("price")
MsgBox "価格は:" & element.Text
End Sub
他の取得方法
driver.FindElementByClass("classname").Text
driver.FindElementByCss("div.item span.price").Text
driver.FindElementByXPath("//div[@id='price']").Text
5. 応用:テーブルや価格情報をExcelに自動転記
以下は、複数の要素を取得してExcelのA列に転記する例です。
Sub ScrapeListToExcel()
Dim driver As New WebDriver
Dim items As Object
Dim i As Long
driver.Start "edge", "https://example.com/list"
driver.Get "/"
Set items = driver.FindElementsByCss("ul.product-list li")
For i = 0 To items.Count - 1
Cells(i + 1, 1).Value = items.Item(i).Text
Next i
End Sub
6. よくあるエラーと対処法
エラー内容 | 原因 | 対処法 |
---|---|---|
driver not found | EdgeDriver.exeが見つからない | SeleniumBasicと同じフォルダに配置 |
SeleniumBasicが動作しない | 古いバージョン or Windowsの制限 | 最新のEdgeに対応したSeleniumBasicを使う(GitHubのfork版) |
VBAで New WebDriver が使えない | 参照設定が不足 | VBE → ツール → 参照設定 → Selenium Type Library を追加 |
7. まとめ
- VBAによるWebスクレイピングは、Edge対応が必須の時代へ
- SeleniumBasic + EdgeDriverの組み合わせで、IE廃止後も安定運用が可能
- Excelと連携することで、業務データの自動取得・可視化にも活用できます
定期的なデータ取得や価格監視、在庫情報取得に、VBA × Seleniumは強力な選択肢です。