首页 > 解决方案 > 如何在 Access 中以 csv 格式通过电子邮件发送查询结果

问题描述

我有一个访问数据库,想以 CSV 格式保存查询结果并通过 Outlook 发送电子邮件。有没有办法这样做?

我试过DoCmd.TransferText命令,但找不到具体的

Public Sub export_query()
    DoCmd.TransferText acExportDelim, "Specific", "Query1", "C:\test\Query1.txt", True
End Sub

标签: vbaemailms-accessexport-to-csv

解决方案


如果要使用规范,首先需要通过向导手动导出为文本。您可能还没有保存您的规范,或者您使用了错误的名称。

  1. 打开您的查询。
  2. 在功能区上,选择External Data选项卡。
  3. 选择选项到Export to text。(或者,您可以在导航窗格中右键单击查询并导出为文本)
  4. 当向导出现时,不要勾选提供给您的任何选项,然后单击OK
  5. 在助手屏幕中,单击Advanced
  6. 根据您的喜好设置规格。
  7. 单击Save as以保存您的规范并为其命名。

确保在您的DoCmd.TransferText. 此外,将扩展名更改为.csv而不是.txt输出文件名参数。

您可以使用以下功能导出和通过电子邮件发送您的.csv

Sub export_query()
    Dim objOutlook As Outlook.Application
    Dim objMail As Outlook.MailItem

    Set objOutlook = CreateObject("Outlook.Application")
    Set objMail = objOutlook.CreateItem(olMailItem)

    ' Export to CSV
    DoCmd.TransferText acExportDelim, "Specific", "Query1", "C:\test\Query1.csv", True
    ' You could also try it without any specifications. (Untested)
    ' DoCmd.TransferText acExportDelim, "", "Query1", "C:\test\Query1.csv", True

    ' Send the email
    With objMail
        .To = "John@Doe.com"
        .Subject = "This is the subject."
        .Body = "This is the body."
        .Attachments.Add ("C:\test\Query1.csv")
        .Display '(If you want to see the email and send it yourself)
        '.Send '(If you want to send the email without seeing it)
    End With

    ' Clean up the objects
    Set objMail = Nothing
    Set objOutlook = Nothing
End Sub

推荐阅读