【问题标题】:VB.Net Add Workbook to Running EXCEL InstanceVB.Net 将工作簿添加到运行 EXCEL 实例
【发布时间】:2022-11-01 12:58:30
【问题描述】:

我正在开发 AutoCAD 插件。试图实现它首先查找已经运行的 EXCEL 实例的功能,所以我只是将新工作簿添加到现有实例,而不是总是创建新进程。

我的代码在尝试查找正在运行的进程时失败。由于某种原因,它总是检测到正在运行的 EXCEL 进程,我在任务管理器中检查了它,它不存在所以这就是为什么我的插件在 Marchal.GetActiveObject 方法崩溃的原因,因为它试图让那个正在运行的进程......

到目前为止我的函数代码:

Private Function GetExcelWorksheet() As Excel.Worksheet

    Dim excel As Excel.Application
    Dim activeWorksheet As Excel.Worksheet = Nothing
    Dim wb As Excel.Workbook = Nothing
    Dim ws As Excel.Worksheet = Nothing


    Dim ExcelInstances As Process() = Process.GetProcessesByName("EXCEL")
    If ExcelInstances.Count() = 0 Then
        Exit Function
    End If

    excel = TryCast(Marshal.GetActiveObject("Excel.Application"), Excel.Application)
    If excel Is Nothing Then Exit Function

    excel.Visible = True
    wb = excel.Workbooks.Add
    ws = wb.Worksheets(1)
    Return ws

End Function

【问题讨论】:

    标签: excel vb.net autocad-plugin


    【解决方案1】:
    Imports System
    Imports System.Runtime.InteropServices
    
    Public Module AnythingYouWantToCallIt
    
    
        Sub Main
            Dim Excel as Object
            Dim wb as Object
            Dim WS as Object
            On Error Resume Next
            Excel = GetObject(, "Excel.Application")
            If Err.number = 429 then
                Msgbox("No Excel running")
                err.clear
                Excel = CreateObject("Excel.Application")
                If err.number = 429 then
                    MsgBox(err.number)
                    MsgBox("Excel Not Installed")
                    err.clear
                Else
                    MsgBox("New Excel has started")
                End If
            Else
                Msgbox("Existing Excel connected to")               
            End If
            WB = Excel.Workbooks.Add
            WS = wb.Worksheets(1)
            MsgBox(ws.name)
            'If in a function
            'Main = WS
        End Sub 
    End Module
    
     
    

    这是基本的方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-21
      • 2017-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-10
      • 1970-01-01
      相关资源
      最近更新 更多