VBA 使用 Outlook 打开 excel 打不开

VBA Using Outlook to open excel not opening

您好,感谢您的帮助。

我在 Outlook 2010 和 2007 中有以下代码:

Sub Openexcel()
    Dim xlApp As Object
    Dim sourceWB As Workbook
    Dim sourceSH As Worksheet
    Dim strFile As String
    Set xlApp = CreateObject("Excel.Application")
    With xlApp
        .Visible = True
        .EnableEvents = False
    End With

    strFile = "E:\All documents\susan\work\Excel projects\saving files to directory Clean.xls"

    Set sourceWB = Workbooks.Open(strFile, , False, , , , , , , True)
    Set sourceSH = sourceWB.Worksheets("Sheet2")
    sourceWB.Activate
End Sub

此代码在我打开 Outlook 后第一次使用它时有效,但如果我随后关闭 excel 文件,我将无法再次使用它。我需要重新打开这本工作簿大约 3 次

问题
Outlook VBA open excel 看到有同样的问题,但我没看懂答案。

"I got it figured out. I was opening a different workbook and then closing it before I try to open the second one and that was interfering with it. To fix this I kept the excel app open and reset the workbook object to the new workbook i wanted"

如果有人可以帮助提供额外的代码,那就太好了。

您需要在全局范围内声明 Excel 应用程序并使用它打开另一个工作簿。不创建用于打开新文件的新 Excel 实例。您可能会发现 How to automate Microsoft Excel from Visual Basic 文章很有帮助。

例如,在事件处理程序外声明Application对象:

Dim oXL As Excel.Application

Private Sub Command1_Click()
   Dim oWB As Excel.Workbook

因此,您将能够重新使用它来关闭和打开新的工作簿。

Excel interactions don't work after Excel file opened 找到了很棒的代码。

为什么我上周找不到这个谁知道呢。

Sub Openexcel()
' change
  Dim xlApp As Excel.Application
  Dim sourceWB As Excel.Workbook
  Dim sourceSH As Excel.Worksheet
'change
  Set xlApp = New Excel.Application
      With xlApp
      .Visible = True
      .EnableEvents = False
      '.UserControl = False
       '.DisplayAlerts = False
       '.AskToUpdateLinks = False

End With

strFile = "E:\All documents\susan\work\Excel projects\saving files to directory Clean.xls"
'change
Set sourceWB = xlApp.Workbooks.Open(strFile, , False, , , , , , , True)
Set sourceSH = sourceWB.Worksheets("Sheet2")
sourceWB.Activate

End Sub

感谢你们的所有想法。