excel - 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 需要做的事情
解决方案
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
推荐阅读
- javascript - 迭代嵌套的 JSON 数组
- r - 使用 %in% 运算符在 R 中进行部分字符串匹配?
- php - 如何创建 GROUP BY SQL 语句
- count - 如何用我当前的问题计算 cakePHP 中的分组(groupby / group)记录?
- youtube - 如何切换 youtube 视频上的字幕?
- react-native - 错误:任务“:app:processDebugManifest”执行失败
- html - Angular 7:选择标签不显示选项
- javascript - 我如何在我的 Google App Maker 应用程序中使用绑定到我的文档的 Apps 脚本中的函数?
- reactjs - HapiJS + create-react-app + webpack-dev-middleware 配置
- docker - 如何创建正确的 Dockerfile