Excel中的录制宏在运行时失败

时间:2011-04-05 21:33:12

标签: excel vba excel-vba excel-2007

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

录制的宏失败,如评论中所述。

1 个答案:

答案 0 :(得分:4)

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

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

修改 (以回应评论):

  

我需要能够将查询结果粘贴到不同的工作表然后是活动工作表,因为宏可以随时运行,并且必须每次粘贴到同一位置。也许有办法用代码更改活动表?

当两张纸不同时会发生错误,因此如果您希望在特定纸张上发生魔术,则应指定该纸张而不是ActiveSheet。以下代码总是将QueryTable放在Sheet6上:

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