在多个excel实例运行期间检索所有工作簿名称

这个问题基本上是关于循环所有excel实例中的所有工作簿!

您面临的主要问题是您没有使用您遇到的任何stream程。 因此,你不会得到任何东西。 在进程的循环内部,您将创build一个新的ExcelApplication实例,然后尝试循环执行Workbooks 。 默认情况下,当你这样做的时候,这个时候只有1个 ,所以你只有1个 Workbook ,为什么你只能看到1个 Workbook

解决scheme(试验&testing)

您需要查看Windows API调用以获取所需内容。 其中一些是:

  1. GetDesktopWindow()
  2. EnumChildWindows()
  3. GetClassName()
  4. EnumWindowsProc()
  5. AccessibleObjectFromWindow()

     Imports Microsoft.Office.Interop Imports System.Runtime.InteropServices Public Class Form1 Private Declare Function GetDesktopWindow Lib "user32" () As Integer Private Declare Function EnumChildWindows Lib "user32.dll" (ByVal WindowHandle As IntPtr, ByVal Callback As EnumWindowsProc, ByVal lParam As IntPtr) As Boolean Private Declare Function GetClassName Lib "user32.dll" Alias "GetClassNameA" (ByVal hWnd As IntPtr, ByVal lpClassName As String, ByVal nMaxCount As Integer) As Integer Private Delegate Function EnumWindowsProc(ByVal hwnd As IntPtr, ByVal lParam As Int32) As Boolean Private Declare Function AccessibleObjectFromWindow Lib "oleacc" (ByVal Hwnd As Int32, ByVal dwId As Int32, ByRef riid As Guid, <MarshalAs(UnmanagedType.IUnknown)> ByRef ppvObject As Object) As Int32 Private Const OBJID_NATIVE = &HFFFFFFF0 'Required to show the workbooks. Used in function to add to. Private lstWorkBooks As New List(Of String) Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click lstWorkBooks.Clear() GetExcelOpenWorkBooks() End Sub Private Sub GetExcelOpenWorkBooks() Try 'Get handle to desktop Dim WindowHandle As IntPtr = GetDesktopWindow() 'Enumerate through the windows (objects) that are open EnumChildWindows(WindowHandle, AddressOf GetExcelWindows, 0) 'List the workbooks out if we have something If lstWorkBooks.Count > 0 Then MsgBox(String.Join(Environment.NewLine, lstWorkBooks)) Catch ex As Exception End Try End Sub Public Function GetExcelWindows(ByVal hwnd As IntPtr, ByVal lParam As Int32) As Boolean Dim Ret As Integer = 0 Dim className As String = Space(255) 'Return the string with some padding... Ret = GetClassName(hwnd, className, 255) className = className.Substring(0, Ret) If className = "EXCEL7" Then Dim ExcelApplication As Excel.Application Dim ExcelObject As Object = Nothing Dim IDispatch As Guid AccessibleObjectFromWindow(hwnd, OBJID_NATIVE, IDispatch, ExcelObject) 'Did we get anything? If ExcelObject IsNot Nothing Then ExcelApplication = ExcelObject.Application 'Make sure we have the instance... If ExcelApplication IsNot Nothing Then 'Go through the workbooks... For Each wrk As Excel.Workbook In ExcelApplication.Workbooks 'If workbook ins't in the list then add it... If Not lstWorkBooks.Contains(wrk.Name) Then lstWorkBooks.Add(wrk.Name) End If Next End If End If End If Return True End Function End Class