【发布时间】:2020-07-13 20:07:33
【问题描述】:
我正在尝试使用 Access VBA 用 Access 查询的输出覆盖 Excel 工作表。我从this post here 获取并修改了一些很棒的 Access VBA 代码。任务完成但最后我得到一个运行时错误:
运行时错误“424”:需要对象
修改后的代码如下。关于为什么会发生这种情况的任何想法?
Option Compare Database
Option Explicit
Private Const strFilePath As String = "C:\Users\MyPC\Desktop\Test Tracker\APS_Timeline_Status.xlsm"
Private Const strTQName As String = "q_APS_Timeline_Status_For_Export"
Private Const strSheetName As String = "TimeLine_Status"
Sub Update_timeline_tracker()
SendTQ2XLWbSheet(strTQName, strSheetName, strFilePath).Run
End Sub
Public Function SendTQ2XLWbSheet(strTQName As String, strSheetName As String, strFilePath As String)
' strTQName is the name of the table or query you want to send to Excel
' strSheetName is the name of the sheet you want to send it to
' strFilePath is the name and path of the file you want to send this data into.
Dim rst As DAO.Recordset
Dim ApXL As Object
Dim xlWBk As Object
Dim xlWSh As Object
Dim fld As DAO.Field
Dim strPath As String
On Error GoTo err_handler
DoCmd.SetWarnings False
strPath = strFilePath
Set rst = CurrentDb.OpenRecordset(strTQName)
Set ApXL = CreateObject("Excel.Application")
Set xlWBk = ApXL.Workbooks.Open(strPath)
Debug.Print strPath
ApXL.Visible = True
Set xlWSh = xlWBk.Worksheets(strSheetName)
ApXL.DisplayAlerts = False
xlWSh.Activate
xlWSh.Range("A1").Select
For Each fld In rst.Fields
ApXL.ActiveCell = fld.Name
ApXL.ActiveCell.Offset(0, 1).Select
Next
rst.MoveFirst
xlWSh.Range("A2").CopyFromRecordset rst
' selects the first cell to unselect all cells
xlWSh.Range("A1").Select
rst.Close
xlWBk.SaveAs FileName:="C:\Users\MyPC\Desktop\Test Tracker\APS_Timeline_Status.xlsm"
xlWBk.Close
ApXL.Quit
Set rst = Nothing
Exit_SendTQ2XLWbSheet:
Exit Function
err_handler:
DoCmd.SetWarnings True
MsgBox Err.Description, vbExclamation, Err.Number
Resume Exit_SendTQ2XLWbSheet
DoCmd.SetWarnings True
End Function
【问题讨论】:
-
如果您将
private const设为public const,会发生什么?它们不在程序范围内,所以我认为它应该是公开的 -
嗨,利亚姆。我已将所有私有 const 更改为公共 const。发现相同的运行时错误。
-
我看不到未定义的对象。如果您删除错误处理,您的错误会出现在哪一行?
-
谢谢利亚姆。当我调试错误时,它把我带到了这里:
SendTQ2XLWbSheet(strTQName, strSheetName, strFilePath).Run,当我向下移动代码时,错误专门出现在End Function
标签: ms-access vba runtime-error