【问题标题】:Access File creating Excel With MessageBox使用 MessageBox 访问文件创建 Excel
【发布时间】:2018-07-10 12:04:54
【问题描述】:

我的 Access File 从数据库中提取数据并将其转换为自动生成并通过电子邮件发送的 excel 文件。我想不通的是如何让excel文件在关闭excel文件时弹出一个消息框。我知道这是可以做到的,因为我在常规的 excel 文件上已经做过很多次了。

我认为问题在于仅生成 .xlsx 文件而不是 .xlsm 文件的访问文件。或者我尝试使用的 VBA 代码不正确(无论是放置代码还是代码本身。

如果你能解决它并且想知道消息框应该说什么,我只想说“你完成任务了吗?”是/否框没什么疯狂的。

FilePath = "\\ms000ew01\Departments\Reporting\Reports"
FileName = FilePath & "\" & GrName & ShipDate & Timestamp
Attachfile = FileName & ".xlsm"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "Draft", 
FileName, True
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "Turn", 
FileName, True
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "Final", 
FileName, True

Dim xlApp As Object
    Set xlApp = CreateObject("Excel.Application")
    With xlApp
    .Visible = False
    .Workbooks.Open (FileName & ".xlsm")
    .Sheets("Draft").Select
    .ActiveSheet.UsedRange.Font.Name = "Tahoma"
    .ActiveSheet.UsedRange.Font.Size = 8
    xlApp.Cells.EntireColumn.AutoFit
    xlApp.Cells.EntireRow.AutoFit
    .Sheets("Turn").Select
     .ActiveSheet.UsedRange.Font.Name = "Tahoma"
    .ActiveSheet.UsedRange.Font.Size = 8
    xlApp.Cells.EntireColumn.AutoFit
    xlApp.Cells.EntireRow.AutoFit
     .Sheets("Final").Select
     .ActiveSheet.UsedRange.Font.Name = "Tahoma"
    .ActiveSheet.UsedRange.Font.Size = 8
    xlApp.Cells.EntireColumn.AutoFit
    xlApp.Cells.EntireRow.AutoFit
    Set xlApp = Nothing

    Dim OutApp As Object
    Dim MailObj As Object
    Set OutApp = CreateObject("Outlook.Application")
    Set MailObj = OutApp.CreateItem(olMailItem)

With MailObj
.To = EmailTo
.Subject = GrName & " Report"
.Body = "Attached is your report"
.Attachments.Add Attachfile
.Send
End With

Set OutApp = Nothing
Set MailObj = Nothing
rst.MoveNext

End With


End Sub

【问题讨论】:

  • An image of your code is not helpful。请在您的问题中包含代码并将其格式化为代码块(至少要有 4 个空格)。
  • 你能粘贴一些代码吗?
  • 欢迎来到Stack Overflow! XLSX 文件不能包含 VBA 代码。您需要生成XLSM。此外,代码图像很难阅读,其他任何人都无法运行;首选粘贴为代码块的复制文本。请查看tour(您将获得徽章!)以及“How to Ask”以及minimal reproducible exampleStack Overflow的顶级用户here还有更多好的提示。
  • 哦,好吧!我改变了它,我也会看看这次旅行。很抱歉给您带来不便。
  • 也许尝试不同的方法?使用您需要的代码手动创建 xlsm 文件。将其保存在访问文件位置。比将数据导出到这个 xlsm 文件(记得删除旧数据)。

标签: excel ms-access vba msgbox


【解决方案1】:

编辑:下面列出的代码已于 2018 年 7 月 16 日星期一更新,以反映自上周发布原始帖子以来我所做的工作。新代码在 Office 2007 中经过了全面测试和功能,但是需要使用正确的文件名、表格、查询、电子邮件地址等进行自定义。总而言之,很高兴我终于得到了这个工作,因为我一直想要以编程方式生成带有嵌入代码的 Access 表单和报告。

我将在这里继续我的评论。换句话说,Access VBA 模块需要将新代码写入 Excel VBA 模块。为了实现这一点,Access VBA 项目需要引用VBIDE aka Microsoft Visual Basic for Applications Extensibility。该库允许对 VBA IDE 的自动化进行相当广泛的访问,也就是您编写代码的窗口。

Chip Pearson(他在 4 月的一场车祸后不幸于 6 月去世)收集了很多关于 VBIDE 编码的页面:cpearson.com/excel/vbe.aspx。不幸的是,我现在在任何 Microsoft 页面上都找不到有用的 VBIDE 命令参考;他们似乎已经删除了除 Office 365 之外的所有内容,剩下的并不多。这遵循了微软长期以来对 VBIDE 文档不足的传统。

我目前正在为我自己的项目解决这个问题,但有一点不同。需要编写的代码是按钮的Click 事件。并且要使用 VBIDE(而不是常规子程序或函数)编写事件,必须使用特殊方法:CreateEventProc。正如我所提到的,我的项目还没有完成,但我已经为你一起破解了这个代码示例。请注意,这是测试的。我会看看我是否可以在今天晚些时候让它真正起作用。我们似乎都有相同的目标,即使用 Access VBA 创建 Excel 工作簿,然后将 VBA 写入其中,所以我有动力让它工作......

Public Function CreateExcelWorkbookWithEvents()

    'This procedure is meant to reside in a Microsoft Access code module.

    'This procedure requires two project references:
    ' 1) Microsoft Excel   XX.Y Object Library (mine is 12.0)
    ' 2) Microsoft Outlook XX.Y Object Library (mine is 12.0)
    ' 3) Microsoft Visual Basic for Applications Extensibility X.Y (mine is 5.3)

    'Project references are always preferred over CreateObject() when possible, since a
    'reference allows the IntelliSense auto-complete to do its job. Otherwise, it's
    'coding blind, and that's just no fun.

    'Access variables.
    Dim acc         As Access.Application
    Dim db          As DAO.Database
    Dim rs          As DAO.Recordset
    Dim rsRows      As Long
    Dim sqlText     As String

    'Excel variables.
    Dim xl          As Excel.Application
    Dim wb          As Excel.Workbook
    Dim wss         As Excel.Sheets
    Dim ws          As Excel.Worksheet
    Dim ws1         As Excel.Worksheet
    Dim ws2         As Excel.Worksheet
    Dim ws3         As Excel.Worksheet
    Dim firstCell   As String

    'VBIDE variables.
    Dim proj        As VBIDE.VBProject
    Dim comp        As VBIDE.VBComponent
    Dim cmod        As VBIDE.CodeModule
    Dim code        As String

    'Outlook variables.
    Dim olapp       As Outlook.Application
    Dim olmsg       As Outlook.MailItem

    'Other variables.
    Dim filepath        As String
    Dim filename        As String
    Dim fileext         As String
    Dim fullFilename    As String
    Dim timestamp       As String

    'Filename construction.
    filepath = "c:\windows\temp"
    filename = "MyWb"
    fileext = "xlsm"
    timestamp = VBA.Format(Now(), "yyyymmddhhnnss")
    fullFilename = filepath & "\" & filename & "_" & timestamp & "." & fileext

    'Access objects.
    Set acc = Access.Application
    Set db = acc.CurrentDb

    'Excel objects.
    Set xl = New Excel.Application

    'Create a new blank WB with one worksheet. The 'xlWBATWorksheet' parameter creates a
    'new blank workbook with only one sheet instead of the usual three. A weird side
    'effect of this is the workbook will have the name "Sheet1" instead of "Book1", but
    'otherwise it's a perfectly normal workbook.
    Set wb = xl.Workbooks.Add(xlWBATWorksheet)

    'Uncomment and change text if desired.
    'xl.Caption = "Workbook Title"

    'Add & name the tabs.
    Set wss = wb.Worksheets
    Set ws1 = wss(1)
    ws1.name = "tmpDraft"
    Set ws2 = wss.Add(, wss(wss.Count), , xlWorksheet)
    ws2.name = "tmpTurn"
    Set ws3 = wss.Add(, wss(wss.Count), , xlWorksheet)
    ws3.name = "tmpFinal"
    ws1.Select 'Go back to the first sheet.

    'Loop through worksheets, use tab names for the queries, dump the data into the sheets,
    'then format them as desired.
    firstCell = "A1" 'Where to put data on each sheet.
    For Each ws In wss
        sqlText = "SELECT * FROM " & ws.name & ""
        Set rs = db.OpenRecordset(sqlText, dbOpenSnapshot, dbFailOnError)
        rsRows = ws.Range(firstCell).CopyFromRecordset(rs) 'This
        Set rs = Nothing
        ws.Cells.Font.name = "Tahoma"
        ws.Cells.Font.size = 8
        ws.Cells.EntireColumn.AutoFit
        ws.Cells.EntireRow.AutoFit
    Next

    'Add the event code. Build the code in a way that's easy to read. Because there are
    'of embedded double-quotes in the strings, this part can get quite messy and
    'difficult to read. So that's why VBA.Replace() is used. It makes the "code of code"
    'much more freindly to human eyes. The code that's built here is only what's
    'between Sub...End Sub, which are created automatically by CreateEventProc().
    '
    'Just as in Microsoft Word, the paragraph character  indicates where a
    'hard-return should be, but something offbeat had to be used to show the double
    'quotes, so the degree symbol ° is used, that being Chr$(176). Although any
    'character(s) which the programmer desires may be used, these were chosen because
    'they do not appear as valid characters in VBA.
    '
    'Note: The section of the code below with the If-Then to detect if Excel is visible
    'are needed because the wb.Close statement further down in this subroutine cause the
    'event we just created to be trigged as if the user is attempting to exit Excel. This
    'seemed to be the simplest way to handle this, with other options such as setting
    'a global variable somehow in Excel while the code is being created, but I didn't\
    'experiment with that.
    '
    code = ""
    code = code & "Private Sub Workbook_BeforeClose(Cancel As Boolean)¶"
    code = code & "Dim xlapp       As Excel.Application¶"
    code = code & "Dim msgResponse As VbMsgBoxResult¶"
    code = code & "Dim msgTitle    As String¶"
    code = code & "Dim msgText     As String¶"
    code = code & "Dim msgStyle    As Long¶"
    code = code & "¶"
    code = code & "'Detect if Excel is hidden, presumably because it was created via automation¶"
    code = code & "'from another program. If so, do not prompt the user to confirm exit.¶"
    code = code & "Set xlapp = Excel.Application¶"
    code = code & "If xlapp.Visible = True Then¶"
    code = code & "    msgTitle = °Confirm Exit°¶"
    code = code & "    msgText = °Are you sure you want to exit?°¶"
    code = code & "    msgStyle = vbApplicationModal + vbExclamation + vbYesNo¶"
    code = code & "    msgResponse = MsgBox(msgText, msgStyle, msgTitle)¶"
    code = code & "    If msgResponse = vbNo Then¶"
    code = code & "        Cancel = True 'This is what cancels the Close event.¶"
    code = code & "    End If¶"
    code = code & "End If¶"
    code = code & "End Sub¶"
    code = VBA.Replace(code, "¶", vbCrLf)       'Replace the ¶ characters with hard returns.
    code = VBA.Replace(code, "°", VBA.Chr(34))  'Replace the ° characters with double quotes.

    'Dig into the VBA Project, create the event, and add the code. NOTE: There is an
    'issue with manipulating code from VBA. You can't step through those lines in debug
    'mode if you are adding code to the SAME file you're working in. For instance, if you're
    'in an XLSM file, adding code to its own ThisWorkbook module. Won't work. It causes a
    'runtime error. I think Chip Pearson mentioned it on his VBIDE pages, but I can't find it.
    Set proj = wb.VBProject                         'Grab the VBA project.
    Set comp = proj.VBComponents("ThisWorkbook")    'Grab the "ThisWorkbook" code module.
    Set cmod = comp.CodeModule                      'Grab the ThisWorkbook code window.
    cmod.InsertLines cmod.CountOfLines + 1, code    'Insert the code.

    'Originally CreateEventProc() was used, but it was found to pop open the VBA IDE
    'window, despite any attempt to prevent it. However, the same goal can be accomplished
    'with the regular InsertLines() function. It's all text in the IDE anyways, and how it
    'gets there doesn't matter. One need only be certain everything is spelled correctly.
    'This is the original attempt:
    'xl.vbe.MainWindow.Visible = False               'Hide the VBA editor from the user.
    'firstLine = cmod.CreateEventProc("BeforeClose", "Workbook") + 1 'Create the event.

    'Save as a macro-enabled workbook. Don't forget: each installation of Excel may need
    'the macros enabled in the security settings.
    wb.SaveAs fullFilename, xlOpenXMLWorkbookMacroEnabled

    'Not sure if this is desired.
    'xl.Visible = True

    'Clear the variables. If the 'xl' variable is not released, lost instances of Excel
    'will start to pile up in memory. They can be seen in Task Manager, but to be properly
    'identified, click View > Select Columns > Command Line > Ok. The instances of Excel
    'started from VBA will have the command line switch '/automation -Embedding' like this:
    '"C:\Program Files (x86)\Microsoft Office\Office12\EXCEL.EXE" /automation -Embedding
    'And even so, these instances of Excel may not unload from memory until this subroutine
    'is finished and exits. It's a fussy thing with a difficult pattern to follow. I find if
    'while devloping the code, when stepping through debug with F8, if I stop the macro
    'prematurely, the automation instances tend to stack up and need to be manually killed.
    wb.Close True
    xl.Quit
    Set wb = Nothing
    Set xl = Nothing

    'Create the email and send it.
    Set olapp = New Outlook.Application
    Set olmsg = olapp.CreateItem(olMailItem)
    olmsg.To = "mshea@certobrothers.com"
    olmsg.Subject = "Report"
    olmsg.Body = "Attached is your report"
    olmsg.Attachments.Add fullFilename, olByValue
    olmsg.Send

    Set olapp = Nothing
    Set olmsg = Nothing

End Function

【讨论】:

  • 糟糕,等等……!我不得不编辑它;事件名称应为 BeforeClose 而不是 Open
  • 你是救世主!我会继续在这里查看更新!
  • @LouVac 好的,伙计,试试吧。我刚刚更新了上面答案中的原始代码,现在大约是原来的两倍。抱歉花了这么长时间。上周忙碌了一周;老板正在休假,而我一个人在管理 IT 部门。 Bin bizzy,大声笑。我确实偏离了您的原始代码,最值得注意的是我使用了 Range.CopyFromRecordset 而不是 DoCmd.TransferSpreadsheet。您必须修改我所做的以适应您的需求。
【解决方案2】:

在此处重新发布以确保@louvac 看到它。我发布了代码作为对我之前答案的修改,但没有收到他的回复。

Public Function CreateExcelWorkbookWithEvents()

    'This procedure is meant to reside in a Microsoft Access code module.

    'This procedure requires two project references:
    ' 1) Microsoft Excel   XX.Y Object Library (mine is 12.0)
    ' 2) Microsoft Outlook XX.Y Object Library (mine is 12.0)
    ' 3) Microsoft Visual Basic for Applications Extensibility X.Y (mine is 5.3)

    'Project references are always preferred over CreateObject() when possible, since a
    'reference allows the IntelliSense auto-complete to do its job. Otherwise, it's
    'coding blind, and that's just no fun.

    'Access variables.
    Dim acc         As Access.Application
    Dim db          As DAO.Database
    Dim rs          As DAO.Recordset
    Dim rsRows      As Long
    Dim sqlText     As String

    'Excel variables.
    Dim xl          As Excel.Application
    Dim wb          As Excel.Workbook
    Dim wss         As Excel.Sheets
    Dim ws          As Excel.Worksheet
    Dim ws1         As Excel.Worksheet
    Dim ws2         As Excel.Worksheet
    Dim ws3         As Excel.Worksheet
    Dim firstCell   As String

    'VBIDE variables.
    Dim proj        As VBIDE.VBProject
    Dim comp        As VBIDE.VBComponent
    Dim cmod        As VBIDE.CodeModule
    Dim code        As String

    'Outlook variables.
    Dim olapp       As Outlook.Application
    Dim olmsg       As Outlook.MailItem

    'Other variables.
    Dim filepath        As String
    Dim filename        As String
    Dim fileext         As String
    Dim fullFilename    As String
    Dim timestamp       As String

    'Filename construction.
    filepath = "c:\windows\temp"
    filename = "MyWb"
    fileext = "xlsm"
    timestamp = VBA.Format(Now(), "yyyymmddhhnnss")
    fullFilename = filepath & "\" & filename & "_" & timestamp & "." & fileext

    'Access objects.
    Set acc = Access.Application
    Set db = acc.CurrentDb

    'Excel objects.
    Set xl = New Excel.Application

    'Create a new blank WB with one worksheet. The 'xlWBATWorksheet' parameter creates a
    'new blank workbook with only one sheet instead of the usual three. A weird side
    'effect of this is the workbook will have the name "Sheet1" instead of "Book1", but
    'otherwise it's a perfectly normal workbook.
    Set wb = xl.Workbooks.Add(xlWBATWorksheet)

    'Uncomment and change text if desired.
    'xl.Caption = "Workbook Title"

    'Add & name the tabs.
    Set wss = wb.Worksheets
    Set ws1 = wss(1)
    ws1.name = "tmpDraft"
    Set ws2 = wss.Add(, wss(wss.Count), , xlWorksheet)
    ws2.name = "tmpTurn"
    Set ws3 = wss.Add(, wss(wss.Count), , xlWorksheet)
    ws3.name = "tmpFinal"
    ws1.Select 'Go back to the first sheet.

    'Loop through worksheets, use tab names for the queries, dump the data into the sheets,
    'then format them as desired.
    firstCell = "A1" 'Where to put data on each sheet.
    For Each ws In wss
        sqlText = "SELECT * FROM " & ws.name & ""
        Set rs = db.OpenRecordset(sqlText, dbOpenSnapshot, dbFailOnError)
        rsRows = ws.Range(firstCell).CopyFromRecordset(rs) 'This
        Set rs = Nothing
        ws.Cells.Font.name = "Tahoma"
        ws.Cells.Font.size = 8
        ws.Cells.EntireColumn.AutoFit
        ws.Cells.EntireRow.AutoFit
    Next

    'Add the event code. Build the code in a way that's easy to read. Because there are
    'embedded double-quotes in the strings, this can get messy and difficult to read.
    'So that's why VBA.Replace() is used. It makes the "code of code" much more freindly
    'to human eyes. The code that's built here is only what's between Sub...End Sub,
    'which are created automatically by CreateEventProc().
    '
    'Just as in Microsoft Word, the paragraph character indicates where a
    'hard-return should be, but something offbeat had to be used to show the double
    'quotes, so the degree symbol ° is used, that being Chr$(176). Although any
    'character(s) which the programmer desires may be used, these were chosen because
    'they do not appear as valid characters in VBA.
    '
    'Note: The section of the code below with the If-Then to detect if Excel is visible
    'are needed because the wb.Close statement further down in this subroutine cause the
    'event we just created to be trigged as if the user is attempting to exit Excel. This
    'seemed to be the simplest way to handle this, with other options such as setting
    'a global variable somehow in Excel while the code is being created, but I didn't
    'experiment with that.
    '
    code = ""
    code = code & "Private Sub Workbook_BeforeClose(Cancel As Boolean)¶"
    code = code & "Dim xlapp       As Excel.Application¶"
    code = code & "Dim msgResponse As VbMsgBoxResult¶"
    code = code & "Dim msgTitle    As String¶"
    code = code & "Dim msgText     As String¶"
    code = code & "Dim msgStyle    As Long¶"
    code = code & "¶"
    code = code & "'Detect if Excel is hidden, presumably because it was created via automation¶"
    code = code & "'from another program. If so, do not prompt the user to confirm exit.¶"
    code = code & "Set xlapp = Excel.Application¶"
    code = code & "If xlapp.Visible = True Then¶"
    code = code & "    msgTitle = °Confirm Exit°¶"
    code = code & "    msgText = °Are you sure you want to exit?°¶"
    code = code & "    msgStyle = vbApplicationModal + vbExclamation + vbYesNo¶"
    code = code & "    msgResponse = MsgBox(msgText, msgStyle, msgTitle)¶"
    code = code & "    If msgResponse = vbNo Then¶"
    code = code & "        Cancel = True 'This is what cancels the Close event.¶"
    code = code & "    End If¶"
    code = code & "End If¶"
    code = code & "End Sub¶"
    code = VBA.Replace(code, "¶", vbCrLf)       'Replace the ¶ characters with hard returns.
    code = VBA.Replace(code, "°", VBA.Chr(34))  'Replace the ° characters with double quotes.

    'Dig into the VBA Project, create the event, and add the code. NOTE: There is an
    'issue with manipulating code from VBA. You can't step through those lines in debug
    'mode if you are adding code to the SAME file you're working in. For instance, if you're
    'in an XLSM file, adding code to its own ThisWorkbook module. Won't work. It causes a
    'runtime error. I think Chip Pearson mentioned it on his VBIDE pages, but I can't find it.
    Set proj = wb.VBProject                         'Grab the VBA project.
    Set comp = proj.VBComponents("ThisWorkbook")    'Grab the "ThisWorkbook" code module.
    Set cmod = comp.CodeModule                      'Grab the ThisWorkbook code window.
    cmod.InsertLines cmod.CountOfLines + 1, code    'Insert the code.

    'Originally CreateEventProc() was used, but it was found to pop open the VBA IDE
    'window, despite any attempt to prevent it. However, the same goal can be accomplished
    'with the regular InsertLines() function. It's all text in the IDE anyways, and how it
    'gets there doesn't matter. One need only be certain everything is spelled correctly.
    'This is the original attempt:
    'xl.vbe.MainWindow.Visible = False               'Hide the VBA editor from the user.
    'firstLine = cmod.CreateEventProc("BeforeClose", "Workbook") + 1 'Create the event.

    'Save as a macro-enabled workbook. Don't forget: each installation of Excel may need
    'the macros enabled in the security settings.
    wb.SaveAs fullFilename, xlOpenXMLWorkbookMacroEnabled

    'Not sure if this is desired.
    'xl.Visible = True

    'Clear the variables. If the 'xl' variable is not released, lost instances of Excel
    'will start to pile up in memory. They can be seen in Task Manager, but to be properly
    'identified, click View > Select Columns > Command Line > Ok. The instances of Excel
    'started from VBA will have the command line switch '/automation -Embedding' like this:
    '"C:\Program Files (x86)\Microsoft Office\Office12\EXCEL.EXE" /automation -Embedding
    'And even so, these instances of Excel may not unload from memory until this subroutine
    'is finished and exits. It's a fussy thing with a difficult pattern to follow. I find if
    'while devloping the code, when stepping through debug with F8, if I stop the macro
    'prematurely, the automation instances tend to stack up and need to be manually killed.
    'Otherwise, rebooting is the only way to get rid of them.
    wb.Close True
    xl.Quit
    Set wb = Nothing
    Set xl = Nothing

    'Create the email and send it.
    Set olapp = New Outlook.Application
    Set olmsg = olapp.CreateItem(olMailItem)
    olmsg.To = "user@email.com"
    olmsg.Subject = "Report"
    olmsg.Body = "Attached is your report"
    olmsg.Attachments.Add fullFilename, olByValue
    olmsg.Send

    Set olapp = Nothing
    Set olmsg = Nothing

End Function

【讨论】:

  • 你是最棒的!我会看看我能用它做什么,但它看起来应该可以完美地工作
  • 优秀。抱歉花了几天时间,工作很忙,我不得不放下它。但好消息是,正如我之前所说,我一直想为自己的报告和其他内容这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-15
  • 1970-01-01
  • 2022-08-20
相关资源
最近更新 更多