如何打开Excel,如果尚未打开

我试图find一种方法来打开Excel使用Outlook VBA,但只有当它尚未打开。 我设法find一些在互联网上打开Excel的代码,做了更改,然后closures它,但如果Excel工作簿已经打开(它确实应用更改,但不再closuresExcel工作簿,它只是把它留在一个灰色的内部;有时它甚至不再显示在资源pipe理器中,我必须从任务pipe理器中closures它)。 我也非常感谢,如果有人能解释大部分的代码。

Public xlApp As Object Public xlWB As Object Public xlSheet As Object Sub ExportToExcel() Dim enviro As String Dim strPath As String 'Get Excel set up enviro = CStr(Environ("USERPROFILE")) 'the path of the workbook strPath = enviro & "\Documents\test2.xlsx" On Error Resume Next Set xlApp = GetObject(, "Excel.Application") If Err <> 0 Then Application.StatusBar = "Please wait while Excel source is opened ... " Set xlApp = CreateObject("Excel.Application") bXStarted = True End If On Error GoTo 0 'Open the workbook to input the data Set xlWB = xlApp.Workbooks.Open(strPath) Set xlSheet = xlWB.Sheets("Sheet1") ' Process the message record On Error Resume Next xlWB.Close 1 If bXStarted Then xlApp.Quit End If End Sub 

我知道xlWbxlSheet对象是做什么的,它们是如何声明的,我也理解environ函数和strPathstring是做什么的,但是我不明白为什么我们需要bXStarted布尔值, Set xlApp = GetObject是做什么的,为什么Application.StatusBar消息没有得到显示, GetObjectCreateObject之间的区别以及为什么需要这么多的错误testing。 提前致谢。

获取对象和创build对象之间的区别是在标题中,将打开excel.application ,如果有错误err<>0则创build一个excel.application 。 我想你会得到一个saveas消息,因为该文件可能没有保存,但打开,并且你正在指示它保存, error resume nexterror resume next跳过它。 尝试保存之前只是一个.close如果你删除on error resume next错误将不会被跳过,并会显示。

 Sub explaination() Dim blnDidICreateExcel As Boolean ' Please read MSDN on boolean Dim objToHoldExcelCreatedOrNot As Object ' Please read MSDN on objects create/get ' Does the user have Excel open, if i try to get it, then there will be an error logically if not Set objToHoldExcelCreatedOrNot = GetObject(, "Excel.Application") ' Was there an error If Err <> 0 Then ' There was, so i need to create one Set objToHoldExcelCreatedOrNot = CreateObject("Excel.Application") blnDidICreateExcel = True ' Yes, i created it End If ' Do the neccessary ' CLose the workbook ' Did i create this Excel, if so tidy up If blnDidICreateExcel Then objToHoldExcelCreatedOrNot.Quit End Sub