vba - Access/VBA Sub 每隔一段时间工作一次,其他时间抛出 1004 错误
问题描述
我正在尝试将数据导出到 excel 并使用 VBA 在导出的文件中构建数据透视表。下面的代码在我第一次打开 Access 时运行时完全按照预期运行。第二次运行它时,我得到一个运行时错误'1004':方法'范围对象'_Global'在我下面标记的行上失败。第三次运行它,它再次完美运行。
我不知道为什么它会起作用然后不起作用。我添加了 wb.Close 和 xl.quit 并在 sub 结束之前将所有内容设置为 Nothing,所以我认为再次运行会很好。
Option Compare Database
Private Sub cmdRunManagerQuery_Click()
Dim mySQL As String
Dim Temp As Variant
DoCmd.TransferSpreadsheet _
acExport, _
acSpreadsheetTypeExcel12Xml, _
"qryManagerQuery", _
"R:\Workpath\Manager Query.xlsx", _
True
Dim xl As Excel.Application
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim lRowCount As Long
Dim myRange As Excel.Range
Set xl = CreateObject("Excel.Application")
strInputFile = "R:\Workpath\Manager Query.xlsx"
Set wb = xl.Workbooks.Open(strInputFile)
Set ws = wb.Sheets("qryManagerQuery")
'Test that I can edit the file
'ws.Range("C250") = "=SUM(C2:C249)"
Dim pvtCache As PivotCache
Dim pvt As PivotTable
Dim StartPvt As String
Dim SrcData As String
Dim i As Integer
Dim pf As String
Dim pf_Name As String
pf = "Number of Records"
pf_Name = "Sum of Number of Records"
i = 2
Do While ws.Range("A" & i).Value <> ""
i = i + 1
Loop
'ERROR OCCURS HERE...
SrcData = ws.Name & "!" & Range("A1:D" & i - 1).Address(ReferenceStyle:=xlR1C1)
Set sht = Sheets.Add
StartPvt = sht.Name & "!" & sht.Range("A3").Address(ReferenceStyle:=xlR1C1)
Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
SourceType:=xlDatabase, _
SourceData:=SrcData)
Set pvt = pvtCache.CreatePivotTable( _
TableDestination:=StartPvt, _
TableName:="PivotTable1")
pvt.PivotFields("1st Level Complete Date").Orientation = xlColumnField
pvt.PivotFields("1st Level Analyst").Orientation = xlRowField
pvt.AddDataField pvt.PivotFields("Number of Records"), pf_Name, xlSum
wb.Save
wb.Close
xl.quit
Set xl = Nothing
Set wb = Nothing
Set ws = Nothing
Set sht = Nothing
Set pvtCache = Nothing
Set pvt = Nothing
MsgBox "Export complete. Files located at R:\Workpath", _
vbInformation, _
"Export Complete"
End Sub
解决方案
推荐阅读
- vim - 按 K 转到 VimHelp 时可以“查看下一个选项”
- excel-formula - 如何根据 Excel 中的计数/重复随机分配组?
- graphql - Apollo / GraphQL / Prisma“登录”突变不会返回所有用户字段
- python - 如何从“tensorflow.python.feature_column”导入“dense_features”?
- c - Cube IDE 和 stm32 - LED 不闪烁
- html - 如何以更好的方式编写和设置 HTML 样式?
- python - 如何将整数拆分为 n 部分(每个整数)?
- symfony4 - Symfony 4.4 Querybuilder 排除周末的所有事件
- sql - 迭代两个循环(CURSOR 和 WHILE)并打印按位置分组的记录
- excel - 使用 Excel 索引/匹配搜索包含数字和文本的列