Search code examples
vbaexcelexcel-2007

Recorded Macro in Excel fails on run


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

The recorded macro fails as described in the comment.


Solution

  • You recorded the macro while Sheet 6 was active, but are now trying to run it on a different sheet. To run the macro for the current active sheet, simply change the code as follows:

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

    Edit: (in response to comment):

    I need to be able to paste the results of the query to a different sheet then the active one since the macro can be run at any time and must be paste to the same location everytime. Perhaps there is a way to change your active sheet with code?

    The error happens when the two sheets are different, so if you want the magic to happen on a particular sheet, you should specify that sheet instead of using ActiveSheet. The following code would always place the QueryTable on Sheet6:

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