VBA Excel文件在后台保持打开状态

时间:2018-08-27 14:50:53

标签: excel vba ms-access

我当前正在使用Microsoft Access上的模块打开Excel文件并将结果粘贴到电子邮件中。该模块运行正常,但是Excel文件在后台保持打开状态。当我尝试使用相同文件运行相同模块时,这会引起问题。

我正在使用的Excel文件也会自动更新日期字段,因此,我还需要先调用close来保存文件,或者忽略保存更改弹出窗口。

Public Function emailPaste(exFile As String, exSheet As String, exRange As String, _
EmailSubject As String, To_Field As String, Optional CC_Field As String)

Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Dim ApXL As Object

Set ApXL = CreateObject("Excel.Application")
ApXL.Workbooks.Open (exFile)


Set rng = Nothing
' Only send the visible cells in the selection.

Set rng = Sheets(exSheet).Range(exRange).SpecialCells(xlCellTypeVisible)

'If rng Is Nothing Then
    'MsgBox "The selection is not a range or the sheet is protected. " & _
           vbNewLine & "Please correct and try again.", vbOKOnly
    'Exit Sub
'End If

With ApXL.Application
    .EnableEvents = False
    .ScreenUpdating = False
End With

Call OpenOutlook
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)


With OutMail
    .To = To_Field
    .CC = CC_Field
    .Subject = EmailSubject
    .HTMLBody = "<BODY style=font-size:12pt;font-family:Calibri> The report: " & EmailSubject & " " & _
"is pasted below. <br><br> Please review it and contact me if there are any issues.<br><br> " _
& RangetoHTML(rng) & ""
    ' In place of the following statement, you can use ".Display" to
    ' display the e-mail message.
    .Display
End With
On Error GoTo 0

With ApXL.Application
    .EnableEvents = True
    .ScreenUpdating = True
End With

ApXL.Quit

Set ApXL = Nothing
Set OutMail = Nothing
Set OutApp = Nothing
End Function

我如何在最后添加不需要的文件即可保存excel文件并关闭它的代码?

2 个答案:

答案 0 :(得分:0)

您必须非常严格地按照相反的顺序打开Excel对象并以相反的顺序关闭它们:

Public Sub RenameWorkSheet()

    Dim xls     As Excel.Application
    Dim wkb     As Excel.Workbook
    Dim wks     As Excel.Worksheet

    Set xls = New Excel.Application
    Set wkb = xls.Workbooks.Open("c:\test\workbook1.xlsx")
    Set wks = wkb.Worksheets(1)

    wks.Name = "My New Name"
    wkb.Close True

    Set wks = Nothing
    Set wkb = Nothing

    xls.Quit

    Set xls = Nothing

End Sub

答案 1 :(得分:0)

  1. 您应尝试告诉应用程序工作表已保存 照原样。
  2. 然后关闭工作表
  3. 然后尝试关闭应用程序。

类似这样的东西:

exFile.Sheets(exSheet).Saved = True
exFile.Sheets(exSheet).Close
ApXL.Quit

或者说,关闭时不必保存...:

exFile.Sheets(exSheet).Close False
ApXL.Quit

我还建议您应该存储对工作表的直接引用,而不是通过活动窗口隐式调用工作表...

类似

dim wsh as Worksheet
set wsh = exFile.Sheets(exSheet)

然后您可以使用变量wsh ...更舒适