我正试图在打开的工作簿中调用第5张。当我从程序中打开工作簿时,我似乎能够做到:
Dim CurrentRun As New Excel.Application
Dim CurrentBook As Excel.Workbook
Dim CurrentSheet As Excel.Worksheet
Private Sub GeneralButtonOpener_Click(sender As Object, e As EventArgs) Handles GeneralButtonOpener.Click
CurrentRun.Visible = True
CurrentBook = CurrentRun.Workbooks.Add(MainTemplatePath)
CurrentSheet = CurrentBook.Worksheets(4)
CurrentSheet.Activate()
End Sub
但是,如果文件已经打开,我调用工作表的所有尝试都失败了:
Dim CurrentRun As Microsoft.Office.Interop.Excel.Application
Dim CurrentBook As Microsoft.Office.Interop.Excel.Workbook
Dim CurrentSheet As Microsoft.Office.Interop.Excel.Worksheet
CurrentRun = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
CurrentBook = CurrentRun.Workbooks
CurrentSheet = CurrentBook.Sheets(4)
CurrentSheet.Activate()
或
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim CurrentRun As Microsoft.Office.Interop.Excel.Application
Dim CurrentBook As Excel.Workbook
Dim CurrentSheet As Excel.Worksheet
CurrentRun = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
CurrentBook = CurrentRun.ActiveWorkbook
CurrentSheet = CurrentBook.Sheets(4)
CurrentSheet.Activate()
End Sub
我看过几个例子,但我无法弄清楚我哪里出错了。这让我感到惊讶,因为这个问题似乎有很多问题。以太指示了解决/解决这个问题的方法,或者我特别做错了什么。
谢谢!
答案 0 :(得分:0)
令我惊讶的是,我发现事实上我在后台运行了几十个Excel实例。当我调试,并启动COM时,启动第一个Excel实例。第二个是在我打开windows窗体(加载项的主要部分)时启动的。
我不知道的是,当抛出异常时,我在Visual Studio中停止了事情,只关闭了第一个Excel实例。我有代码尝试并清理Excel的打开应用程序,但当然没有达到它,因为抛出了异常。
在这里,我一直在想,当我的东西更加发达时,我会把错误处理放在路上。显然,我需要在构建过程中更早地解决一些基本的错误处理问题。我完全是自学成才,并以某种方式使它成为三年而不是一个问题。
希望其他没有被教过的人可以在拔掉头发14个小时之前看到这个。
<强>解决方案强> 关闭所有其他Excel实例,上面的代码可以正常工作。在错误处理中解决清理问题,并在此处解决:http://support.microsoft.com/kb/317109 也许还会打电话给GC,尽管这似乎有争议。
最终代码:
....
Imports System.Runtime.InteropServices
....
Dim CurrentRun As New Excel.Application
Dim CurrentBook As Excel.Workbook
Dim CurrentSheet As Excel.Worksheet
....
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
On Error GoTo VortexInYourSoul
CurrentRun = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
CurrentBook = CurrentRun.Workbooks(1)
CurrentRun.Visible = True
CurrentSheet = CurrentBook.Sheets(8)
CurrentSheet.Activate()
CurrentBook.ActiveSheet.name = "LLAMA LALA LLAMALMALMAL"
....
Exit Sub
VortexInYourSoul:
CurrentSheet = Nothing
CurrentBook.Close(False)
CurrentBook = Nothing
CurrentRun.Quit()
CurrentRun = Nothing
MsgBox("Error: " & Err.Description)
End Sub