下载数据vba运行时错误5

Sub Download() Dim fromCurr As String, endDate As String, str As String fromCurr = Sheets("Currencies").Range("fromCurr").Value endDate = Sheets("Currencies").Range("endDate").Value Sheets("Data").Cells.Clear str = "http://www.xe.com/currencytables/?from=" _ & fromCurr _ & "&date=" _ & Year(endDate) & "-" & Month(endDate) & "-" & Day(endDate) With Sheets("Data").QueryTables.Add(Connection:= _ "URL;" & str, Destination _ :=Range("$D$3")) .FieldNames = True .RowNumbers = False .FillAdjacentFormulas = False .PreserveFormatting = True .RefreshOnFileOpen = False .BackgroundQuery = True .RefreshStyle = xlInsertDeleteCells .SavePassword = False .SaveData = True .AdjustColumnWidth = True .RefreshPeriod = 0 .WebSelectionType = xlSpecifiedTables .WebFormatting = xlWebFormattingNone .WebTables = """historicalRateTbl""" .WebPreFormattedTextToColumns = True .WebConsecutiveDelimitersAsOne = True .WebSingleBlockTextImport = False .WebDisableDateRecognition = False .WebDisableRedirections = False .Refresh BackgroundQuery:=False End With End Sub 

我试图从指定的货币和数据网站下载货币数据。 (从这个网站http://www.xe.com/currencytables/?from=DKK&date=2017-04-18 )

每当我运行我的macros,我得到运行时错误5。

我改变了你的date格式强制两位数的月份和date,摆脱了Range(“D3”)的ActiveSheet父级。 这适用于我在=范围(“endDate”)= TODAY()。

 Option Explicit Sub Download() Dim fromCurr As String, endDate As Long, str As String fromCurr = Worksheets("Currencies").Range("fromCurr").Value endDate = Worksheets("Currencies").Range("endDate").Value Worksheets("Data").Cells.Clear str = "http://www.xe.com/currencytables/?from=" _ & fromCurr _ & "&date=" _ & Format(endDate, "yyyy-mm-dd") Debug.Print str With Worksheets("Data") With .QueryTables.Add(Connection:="URL;" & str, Destination:=.Range("D3")) .FieldNames = True .RowNumbers = False .FillAdjacentFormulas = False .PreserveFormatting = True .RefreshOnFileOpen = False .BackgroundQuery = True .RefreshStyle = xlInsertDeleteCells .SavePassword = False .SaveData = True .AdjustColumnWidth = True .RefreshPeriod = 0 .WebSelectionType = xlSpecifiedTables .WebFormatting = xlWebFormattingNone .WebTables = """historicalRateTbl""" .WebPreFormattedTextToColumns = True .WebConsecutiveDelimitersAsOne = True .WebSingleBlockTextImport = False .WebDisableDateRecognition = False .WebDisableRedirections = False .Refresh BackgroundQuery:=False End With End With End Sub