从Access VBA覆盖电子表格时出现运行时错误424

时间:2016-05-27 00:43:25

标签: access-vba runtime-error

我正在尝试使用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

1 个答案:

答案 0 :(得分:1)

我认为这里的问题是SendTQ2XLWbSheet是一个函数,而不是一个对象。因此,过程的.run部分无法运行不是对象的东西。这就是您的错误表明需要对象的原因。

要以您需要的方式“运行”子或函数,您必须使用术语“调用”,因此解决方案是:

Sub Update_timeline_tracker()

    call SendTQ2XLWbSheet(strTQName, strSheetName, strFilePath)

End Sub