VBA检查文件(来自网站)是否存在

May*_*you 2 excel vba excel-vba

请耐心等待我,因为我是VBA的初学者.

我试图通过使用VBA的网站打开excel文件.文件的地址(路径)每月更改一次.例如:

问题是我从未预先知道本月的新文件何时发布.因此,我需要检查VBA代码是否存在当前月份文件,如果不存在,我只需打开上个月的文件.

这是我尝试过的:

Dim DirFile As String
Dim wbA As Workbook

DirFile = "http://www.clevelandfed.org/research/data/inflation_expectations/" & Format(Now, "YYYY") & "/" & Format(Now, "MMMM") & "/excel1.xls"

' Check if the file for current month does not exist, open previous month's file
If Len(Dir(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)

'If the current month file exists, open it
Else
    Set wbA = Workbooks.Open(DirFile, IgnoreReadOnlyRecommended:=True)
End If
Run Code Online (Sandbox Code Playgroud)

但是,这会导致错误:

在此输入图像描述

我假设这是因为这是一个驻留在网站上的文件.有人可以帮忙解决这个问题吗?

谢谢!

eve*_*ime 7

假设Dir()对于驻留在网站上的文件不起作用,你是正确的

Dir函数 返回一个String,表示与指定的模式或文件属性或驱动器的卷标签匹配的文件,目录或文件夹的名称.

您需要的是以下函数来检查URL是否有效, PS将函数放在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
Run Code Online (Sandbox Code Playgroud)

然后使用宏中的功能

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
Run Code Online (Sandbox Code Playgroud)