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

作为VBA的初学者,请耐心等待。

我想通过使用VBA的网站打开一个excel文件。 文件的地址(path)每个月都在变化。 例如:

  • 七月份,文件名是: http : //www.clevelandfed.org/research/data/inflation_expectations/2014/July/excel1.xls

  • 8月份,文件名为: http : //www.clevelandfed.org/research/data/inflation_expectations/2014/August/excel1.xls

问题是,我不会提前知道当月的新文件将要发布。 因此,如果当前月份文件存在,我需要检查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 

但是,这会导致错误:

在这里输入图像描述

我假设这是由于这是一个驻留在网站上的文件。 任何人都可以请帮助解决这个问题?

谢谢!

假设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 

然后使用你的macros中的function

 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 

这是一个替代scheme。 试着打开它,看看是否失败。 如果是这样,上个月开放。 不是更好,只是不同而已。

 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