首页 > 解决方案 > VBA在循环内向查询表添加新行

问题描述

我有一个 excel 工作簿,其中包含约 100 个 SQL 连接表,这些表位于单独的工作表上,每周都会刷新。我当前的代码是一个循环宏(如下),它遍历每个工作表并刷新每个表。

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

我想要做的是,一旦表格刷新,在每个表格的底部添加一个新行,其中包含第一列中的当前日期。我尝试过使用下面的代码,然后在循环中调用它,但我遇到了各种我不太理解的错误。每个表的列数完全相同,但根据参数的变化具有不同的行。

Dim newrow As ListRow

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

With newrow
   .Range(1) = Date
End With

错误示例;

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

我正在努力了解使用 Excel 2019 需要做的事情

标签: excelvbaloopslistobject

解决方案


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

推荐阅读