简体   繁体   English

访问导出子表单到 excel

[英]Access Export Subform to excel

I'm trying to write some VBA to export filtered records from a subform.我正在尝试编写一些 VBA 来从子表单导出过滤的记录。 I've found a number of post related to this issue and I've cobbled the code below from those post.我发现了许多与此问题相关的帖子,并且我已经从这些帖子中拼凑了下面的代码。

When I run it I get a run-time error saying:当我运行它时,我收到一个运行时错误:

the Object '__temp' already exist.对象 '__temp' 已经存在。

When I click debug it highlights the line当我单击调试时,它会突出显示该行

Set qrydef = db.CreateQueryDef(strTempQryDef, strSQL)

Thank you for you help.谢谢你的帮助。

Private Sub ExportSubform()

    Dim db As dao.Database
    Dim qrydef As dao.QueryDef

    Dim strSQL As String
    Dim bolWithFilterOn As Boolean
    Dim strTempQryDef As String
    Dim strRecordSource As String

    strTempQryDef = "__temp"

    bolWithFilterOn = me.subsearch_frm.Form.FilterOn

    strRecordSource = me.subsearch_frm.Form.RecordSource

    If InStr(strRecordSource, "SELECT ") <> 0 Then
        strSQL = strRecordSource
    Else
        strSQL = "SELECT * FROM [" & strRecordSource & "]"
    End If

    ' just in case our sql string ends with ";"
    strSQL = Replace(strSQL, ";", "")

    If bolWithFilterOn Then
        strSQL = strSQL & _
        IIf(InStr(strSQL, "WHERE ") <> 0, " And ", " Where ") & _
        me.subsearch_frm.Form.Filter
    End If

    Set db = CurrentDb

    'create temporary query
    Set qrydef = db.CreateQueryDef(strTempQryDef, strSQL)
    db.QueryDefs.Append qrydef
    Set qrydef = Nothing

    DoCmd.TransferSpreadsheet TransferType:=acExport, _
    SpreadsheetType:=acSpreadsheetTypeExcel12Xml, _
    TableName:=strTempQryDef, _
    FileName:=Replace(CurrentProject.Path & "\", "\\", "\") & strTempQryDef & ".xlsx"

    ' Delete the temporary query
    db.QueryDefs.Delete strTempQryDef

    Set db = Nothing

End Sub

Per the documentation :根据文档

If the object specified by name is already a member of the QueryDefs collection, a run-time error occurs.如果 name 指定的对象已经是 QueryDefs 集合的成员,则会发生运行时错误。

As such, you should delete the temporary query before attempting to create it.因此,您应该在尝试创建临时查询之前删除它。 To do this, you could use code along the lines of the following:为此,您可以使用以下代码行:

On Error Resume Next
DoCmd.DeleteObject acQuery, strTempQryDef
On Error GoTo 0

Also, per the documentation :此外,根据文档

In a Microsoft Access workspace, if you provide anything other than a zero-length string for the name when you create a QueryDef, the resulting QueryDef object is automatically appended to the QueryDefs collection.在 Microsoft Access 工作区中,如果您在创建 QueryDef 时为名称提供零长度字符串以外的任何内容则生成的 QueryDef 对象将自动附加到 QueryDefs 集合。

As such, you don't need this line:因此,您不需要这一行:

db.QueryDefs.Append qrydef

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM