ray88’s diary

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

VBA 指定のURLよりファイルをDLする

ExcelVBA 目次 - ray88’s diary
APIを使用して指定のURLに格納されているファイルをDLする

Option Explicit
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

Sub Download_File()
Dim lngRes As Long
Dim strURL As String
Dim strPath As String
     
    strPath = "C:\Users\ユーザ名\デスクトップ\ExcelVBAプロジェクト\札幌駅周辺.pdf"
    strURL = "https://www.au.com/content/dam/au-com/mobile/area/5g/downtown/pdf/mb_5g_downtown_oyama.pdf"
    
    lngRes = URLDownloadToFile(0, strURL, strPath, 0, 0)
    If lngRes = 0 Then
        MsgBox "ダウンロード完了!"
    Else
        MsgBox "ファイルをダウンロードできませんでした"
    End If
End Sub

※参考URL 
【エクセルVBA】 URLDownloadToFile関数を使って指定ファイルをワンクリックでダウンロードする方法
VBAでインターネット上のファイルをダウンロードする方法をまとめてみました。 | 初心者備忘録