Can I fix a run time error 9 after adding an Automatic Query?

Viewed 34

I am relatively new to the world of VBA coding and am experiencing an issue that troubleshooting on my own is not allowing me to fix. Every morning I manually refresh a query of 2 files associated to 2 different tabs in the same workbook. The resulting tables are then manipulated by a macro I created, "unlisting" the tables and then further formatting them. So I thought that adding the data queries into my existing macro was a great idea, initially encountering run-time error 1004, which I overcame by re-recording the entire macro, ensuring that I turned off the option to "Enable background refresh," but now I am being plagued by a run-time error 9. Here is my code for the entire macro:

Sub AM_1()
'
' AM_1 Macro
' Newest corrections 03.19.2021
'

'
    With ActiveWorkbook.Connections("Query - mtbt").OLEDBConnection
        .BackgroundQuery = False
        .CommandText = Array("SELECT * FROM [mtbt]")
        .CommandType = xlCmdSql
        .Connection = _
        "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=mtbt;Extended Properties="""""
        .RefreshOnFileOpen = False
        .SavePassword = False
        .SourceConnectionFile = ""
        .SourceDataFile = ""
        .ServerCredentialsMethod = xlCredentialsMethodIntegrated
        .AlwaysUseConnectionFile = False
    End With
    With ActiveWorkbook.Connections("Query - mtbt")
        .Name = "Query - mtbt"
        .Description = "Connection to the 'mtbt' query in the workbook."
    End With
    With ActiveWorkbook.Connections("Query - mtbm").OLEDBConnection
        .BackgroundQuery = False
        .CommandText = Array("SELECT * FROM [mtbm]")
        .CommandType = xlCmdSql
        .Connection = _
        "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=mtbm;Extended Properties="""""
        .RefreshOnFileOpen = False
        .SavePassword = False
        .SourceConnectionFile = ""
        .SourceDataFile = ""
        .ServerCredentialsMethod = xlCredentialsMethodIntegrated
        .AlwaysUseConnectionFile = False
    End With
    With ActiveWorkbook.Connections("Query - mtbm")
        .Name = "Query - mtbm"
        .Description = "Connection to the 'mtbm' query in the workbook."
    End With
    ActiveWorkbook.Connections("Query - mtbm").Refresh
    ActiveWorkbook.Connections("Query - mtbt").Refresh
    ActiveSheet.ListObjects("mtbt").Unlist
    Rows("1:1").Select
    Selection.Delete Shift:=xlUp
    Range("A1:C51").Select
    With Selection.Interior
        .Pattern = xlNone
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
    Selection.Borders(xlDiagonalDown).LineStyle = xlNone
    Selection.Borders(xlDiagonalUp).LineStyle = xlNone
    Selection.Borders(xlEdgeLeft).LineStyle = xlNone
    Selection.Borders(xlEdgeTop).LineStyle = xlNone
    Selection.Borders(xlEdgeBottom).LineStyle = xlNone
    Selection.Borders(xlEdgeRight).LineStyle = xlNone
    Selection.Borders(xlInsideVertical).LineStyle = xlNone
    Selection.Borders(xlInsideHorizontal).LineStyle = xlNone
    With Selection.Font
        .Color = -16776961
        .TintAndShade = 0
    End With
    ActiveWorkbook.Worksheets("mtbm").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("mtbm").Sort.SortFields.Add2 Key:=Range("C1:C300") _
        , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("mtbm").Sort
        .SetRange Range("A1:C300")
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    Range("B1:B300").Select
    Selection.NumberFormat = "#,##0.00"
    Columns("B:B").EntireColumn.AutoFit
    Columns("C:C").Select
    Selection.ColumnWidth = 71
    Range("A1:C300").Select
    With Selection.Font
        .Name = "Calibri"
        .Size = 14
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .Color = -16776961
        .TintAndShade = 0
        .ThemeFont = xlThemeFontMinor
    End With
    ActiveWindow.Zoom = 85
    ActiveWindow.Zoom = 70
    ActiveWindow.Zoom = 55
    Columns("B:B").Select
    Columns("B:B").EntireColumn.AutoFit
    Sheets("mtbt").Select
    Range("B1:B51").Select
    Selection.NumberFormat = "#,##0.00"
    Range("A1:C51").Select
    With Selection.Font
        .Name = "Calibri"
        .Size = 14
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .Color = -16776961
        .TintAndShade = 0
        .ThemeFont = xlThemeFontMinor
    End With
    Sheets("mtbm").Select
End Sub

Right after the "refresh" actions the next line is to "unlist" the "mtbt" table created in the tab with the same name, but that is where it gives me the error.

Any help would be greatly appreciated... Thanks!

1 Answers

Assuming the code creates a new list object whenever it's run, you could try using ActiveSheet.ListObjects.Count to refer to the new list object.

I've added that in the code below, and removed all the Select/Selection stuff which isn't needed.

You might also want to replace ActiveSheet throughout with explicit references to the 'mtbt' sheet - you could even add a variable to the code that references the sheet and use that throughout.

Sub AM_1()
'
' AM_1 Macro
' Newest corrections 03.19.2021
'

'
    With ActiveWorkbook.Connections("Query - mtbt").OLEDBConnection
        .BackgroundQuery = False
        .CommandText = Array("SELECT * FROM [mtbt]")
        .CommandType = xlCmdSql
        .Connection = _
        "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=mtbt;Extended Properties="""""
        .RefreshOnFileOpen = False
        .SavePassword = False
        .SourceConnectionFile = ""
        .SourceDataFile = ""
        .ServerCredentialsMethod = xlCredentialsMethodIntegrated
        .AlwaysUseConnectionFile = False
    End With

    With ActiveWorkbook.Connections("Query - mtbt")
        .Name = "Query - mtbt"
        .Description = "Connection to the 'mtbt' query in the workbook."
    End With

    With ActiveWorkbook.Connections("Query - mtbm").OLEDBConnection
        .BackgroundQuery = False
        .CommandText = Array("SELECT * FROM [mtbm]")
        .CommandType = xlCmdSql
        .Connection = _
        "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=mtbm;Extended Properties="""""
        .RefreshOnFileOpen = False
        .SavePassword = False
        .SourceConnectionFile = ""
        .SourceDataFile = ""
        .ServerCredentialsMethod = xlCredentialsMethodIntegrated
        .AlwaysUseConnectionFile = False
    End With

    With ActiveWorkbook.Connections("Query - mtbm")
        .Name = "Query - mtbm"
        .Description = "Connection to the 'mtbm' query in the workbook."
    End With

    ActiveWorkbook.Connections("Query - mtbm").Refresh


    ActiveSheet.ListObjects(ActiveSheet.ListObjects.Count).Unlist
    Rows("1:1").Delete Shift:=xlUp

    With Range("A1:C51")
        With .Interior
            .Pattern = xlNone
            .TintAndShade = 0
            .PatternTintAndShade = 0
        End With

        .Borders(xlDiagonalDown).LineStyle = xlNone
        .Borders(xlDiagonalUp).LineStyle = xlNone
        .Borders(xlEdgeLeft).LineStyle = xlNone
        .Borders(xlEdgeTop).LineStyle = xlNone
        .Borders(xlEdgeBottom).LineStyle = xlNone
        .Borders(xlEdgeRight).LineStyle = xlNone
        .Borders(xlInsideVertical).LineStyle = xlNone
        .Borders(xlInsideHorizontal).LineStyle = xlNone

        With .Font
            .Color = -16776961
            .TintAndShade = 0
        End With
    End With

    ActiveWorkbook.Worksheets("mtbm").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("mtbm").Sort.SortFields.Add2 Key:=Range("C1:C300") _
                                                                , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("mtbm").Sort
        .SetRange Range("A1:C300")
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

    Range("B1:B300").NumberFormat = "#,##0.00"
    Columns("B:B").EntireColumn.AutoFit
    Columns("C:C").ColumnWidth = 71

    With Range("A1:C300").Font
        .Name = "Calibri"
        .Size = 14
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .Color = -16776961
        .TintAndShade = 0
        .ThemeFont = xlThemeFontMinor
    End With


    Columns("B:B").EntireColumn.AutoFit
    Sheets("mtbt").Range("B1:B51").NumberFormat = "#,##0.00"

    With Range("A1:C51").Font
        .Name = "Calibri"
        .Size = 14
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .Color = -16776961
        .TintAndShade = 0
        .ThemeFont = xlThemeFontMinor
    End With

End Sub
Related