Search code examples
excelvbaloopslistobject

VBA to add new row to query table within loop


I have an excel workbook holding ~100 SQL connection tables that are on separate sheets, that are refreshed every week. My current code is a looping macro (below) that goes through each sheet and refreshes each table.

Sub RefreshLoop()

Dim wks As Worksheet
Dim qt As QueryTable
Dim lo As ListObject

For Each wks In ActiveWorkbook.Worksheets

    For Each lo In wks.ListObjects
        If lo.SourceType = 3 Then
            With lo.QueryTable
                .BackgroundQuery = False
                .Refresh
            End With
        End If

    Next lo

    For Each qt In wks.QueryTables
        qt.Refresh BackgroundQuery:=False
    Next qt

Next wks

Set qt = Nothing
Set wks = Nothing

End Sub

What I'm trying to do is once the table has refreshed, add in a new row to the bottom of each table that contains the current date in the first column. I've tried using the below and then call this within the loop but I'm coming up with all sort of errors that I can't quite understand. Each table is exactly the same number of columns, but with varying rows depending on a change of parameter.

Dim newrow As ListRow

Set newrow = lo.ListRows.Add(AlwaysInsert:=True)

With newrow
   .Range(1) = Date
End With

Example of error;

 Run-time error '91':
 Object variable or With block variable not set

I'm struggling to get my head around what I need to do using Excel 2019


Solution

  • Sub RefreshLoop()
    
    Dim wks As Worksheet
    Dim qt As QueryTable
    Dim lo As ListObject
    
    For Each wks In ActiveWorkbook.Worksheets
    
        For Each lo In wks.ListObjects
            If lo.SourceType = 3 Then
                With lo.QueryTable
                    .BackgroundQuery = False
                    .Refresh
                End With
            End If
            If lo.ListRows.Count = 0 Then
                lo.ListRows.Add.Range(1) = "No instances of this read code."
            End If
    
            lo.ListRows.Add.Range(1) = Date
        Next lo
    
        For Each qt In wks.QueryTables
            qt.Refresh BackgroundQuery:=False
        Next qt
    
    Next wks
    
    Set qt = Nothing
    Set wks = Nothing
    
    End Sub