VBA Check if file (from website) exists

前端 未结 2 1488
孤街浪徒
孤街浪徒 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:11

    Here's an alternative. Just try to open it and see if it fails. If it does, open last months. Not better, just different.

    Public Function GetCFWorkbook() As Workbook
    
        Dim wb As Workbook
        Dim dt As Date
    
        dt = Now
    
        Const sURL As String = "http://www.clevelandfed.org/research/data/inflation_expectations/"
    
        On Error Resume Next
        Application.DisplayAlerts = False
            Set wb = Workbooks.Open(sURL & Format(dt, "yyyy/mmmm") & "/excel1.xls")
        Application.DisplayAlerts = True
        On Error GoTo 0
    
        If wb Is Nothing Then
            Set wb = Workbooks.Open(sURL & Format(DateAdd("m", -1, dt), "yyyy/mmmm") & "/excel1.xls")
        End If
    
        Set GetCFWorkbook = wb
    
    End Function
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题