Excel中logging的macros在运行时失败

Sub Macro3() With ActiveSheet.QueryTables.Add(Connection:= _ "URL;http://..." _ , Destination:=Range("Sheet6!$G$23")) ''// The line above fails with the error: ''// "Run-time error '-2147024809 (80070057)': ''// The destination range is not on the same worksheet ''// that the Query table is being created on." .Name = _ "?tmp=toolbar_FlvTube_homepage&prt=..." .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 End With End Sub 

录制的macros如注释中所述失败。

您在工作表6处于活动状态时录制了macros,但现在正试图在另一张工作表上运行它。 要运行当前活动工作表的macros,只需更改代码,如下所示:

 Sub Macro3() With ActiveSheet.QueryTables.Add(Connection:= _ "URL;http://..." _ , Destination:=ActiveSheet.Range("$G$23")) ... End With End Sub 

编辑:(回复评论):

我需要能够将查询的结果粘贴到不同的工作表,然后是活动的,因为macros可以在任何时候运行,并且必须每次粘贴到相同的位置。 也许有一种方法来改变你的积极工作表的代码?

当两个表单不同时发生错误,所以如果您希望在特定工作表上发生魔法,您应该指定该工作表而不是使用ActiveSheet 。 下面的代码总是将QueryTable放在Sheet6上:

 Sub Macro3() With Sheet6.QueryTables.Add(Connection:= _ "URL;http://..." _ , Destination:=Sheet6.Range("$G$23")) ... End With End Sub