VBA Check if file (from website) exists

前端 未结 2 1492
孤街浪徒
孤街浪徒 2020-12-04 00:46

Please bear with me as I am a beginner at VBA.

I am trying to open an excel file through a website using VBA. The address (path) of the file changes from month to mo

2条回答
  •  星月不相逢
    2020-12-04 01:13

    You are correct in assuming Dir() doesn't work for files residing on Websites

    Dir Function Returns a String representing the name of a file, directory, or folder that matches a specified pattern or file attribute, or the volume label of a drive.

    What you need is the following function to check if the URL is valid, P.S. Place the function in Module

    Function URLExists(url As String) As Boolean
        Dim Request As Object
        Dim ff As Integer
        Dim rc As Variant
    
        On Error GoTo EndNow
        Set Request = CreateObject("WinHttp.WinHttpRequest.5.1")
    
        With Request
          .Open "GET", url, False
          .Send
          rc = .StatusText
        End With
        Set Request = Nothing
        If rc = "OK" Then URLExists = True
    
        Exit Function
    EndNow:
    End Function
    

    Then use the function in your Macro

    If URLExists(DirFile) = 0 Then
        Set wbA = Workbooks.Open("http://www.clevelandfed.org/research/data/inflation_expectations/" & Format(Now, "YYYY") & "/" & Format(DateAdd("m", -1, Date), "MMMM") & "/excel1.xls", IgnoreReadOnlyRecommended:=True)
        wbA.Activate
    'If the current month file exists, open it
    Else
        Set wbA = Workbooks.Open(DirFile, IgnoreReadOnlyRecommended:=True)
    End If
    

提交回复
热议问题