VBA Excel QueryTables.add。刷新BackgroundQuery错误

Sub Macro1() Dim URL As String Dim Path As String Dim i As Integer For i = 2 To 50 If Range("Prices!E" & i).Value <> 1 Then URL = Range("Prices!D" & i).Text Path = Range("Prices!F" & i).Text End If Sheet19.Activate With ActiveSheet.QueryTables.Add(Connection:= _ "URL;" & URL _ , Destination:=ActiveSheet.Range("$A$1")) .Name = _ "" & Path .FieldNames = True .RowNumbers = False .FillAdjacentFormulas = False .PreserveFormatting = True .RefreshOnFileOpen = False .BackgroundQuery = True .RefreshStyle = xlInsertDeleteCells .SavePassword = False .SaveData = True .AdjustColumnWidth = True .RefreshPeriod = 0 .WebSelectionType = xlEntirePage .WebFormatting = xlWebFormattingNone .WebPreFormattedTextToColumns = True .WebConsecutiveDelimitersAsOne = True .WebSingleBlockTextImport = False .WebDisableDateRecognition = False .WebDisableRedirections = False .Refresh BackgroundQuery:=False //'In the Line above the above //'Run time error '1004 //'An unexpected error has occured End With Next i End Sub 

上面的代码在指定的行上创build一个错误。 谷歌search.Refresh BackgroundQuery显示它在循环中的function是挑剔的。 简单的删除这行就不会在excel中显示出来。

当前的错误消息代码工作正常的第一个价值,然后打破。

对于答案和注释,TLDR:.Refresh BackgroundQuery:= False将会失败,如果您的查询input无效或格式错误。 在这种情况下的问题是…下一个循环被称为单元格使用作为url,没有价值的手段。 然而,只要查询格式不正确,它就会失败。

With语句中的所有前面的行都是设置属性。
.Refresh BackgroundQuery := False是一个方法调用。

刷新应该刷新结果。
后台查询是为了查询SQL数据,是可选的,所以我认为你可以离开它,只是有.Refresh

查询表刷新方法帮助链接

编辑它会出现,有什么问题的url,当它刷新它是无法做到这一点。 可能是代理问题,或者没有连接到networking,或者URL不存在。

解决此问题的唯一方法是在每次迭代后删除活动的查询表。 有用的示例解决scheme提供:

https://social.technet.microsoft.com/Forums/office/en-US/956dc1b6-bd37-4b97-a042-ba2a37f729b6/removing-querytables-and-leaving-the-results?forum=excel

我不知道为什么我的修复工作,但这里是:

我也在for循环中使用了querytables.add,并且添加了.asc文件。 这个错误只是在最后一次添加之后popup – 所以我的程序基本上做了我想要的,但它会中断函数。 在For循环的最后一次运行中,我删除了.Refresh BackgroundQuery:= False语句。 它有必要通过For循环来粘贴我以前所有运行的数据。

基本上我取代了这个:

  .Refresh BackgroundQuery:=False 

有了这个:

  If Index = ctr Then Else .Refresh BackgroundQuery:=False End If