VSTO中的Excel Worksheet.Copy方法遇到问题。要复制的工作表存储为资源文件。每次需要复制模板时都会读取资源文件。第一次导入模板表时,该代码可以正常工作。但是,当我立即删除模板表并尝试插入模板表时,会导致错误。
我试图捕捉到异常。但是代码没有捕获异常,并导致错误和excel崩溃。重新启动excel应用程序后,它会完美地复制工作表。在任何一次会议上,我只能导入一次模板。
Dim tempName As String
Dim oTemplate As Excel.Workbook
Try
ResMgr = New Resources.ResourceManager("MYUtilities.Resources",
System.Reflection.Assembly.GetExecutingAssembly)
tempName = "template.xlsx"
tempName = Globals.ThisAddIn.Application.ActiveWorkbook.Path & "\" &
tempName
Dim fstream As New FileStream(tempName, FileMode.Create,
FileAccess.Write)
Dim filestreamWrite As New BinaryWriter(fstream)
filestreamWrite.Write(My.Resources.template, 0,
My.Resources.template.Length)
fstream.Close()
filestreamWrite.Close()
oTemplate = xlApp.Workbooks.Add(tempName)
If Not WorksheetExists("TemplateSheet") Then
oTemplate.Worksheets.Copy(, wb.Worksheets("StartSheet"))
End If
oTemplate.Close()
My.Computer.FileSystem.DeleteFile(tempName)
ResMgr.ReleaseAllResources()
MessageBox.Show("Template Sheet Added...")
Catch ex As Exception
oTemplate.Close() 'line inserted during the trial
My.Computer.FileSystem.DeleteFile(tempName) 'trial line
ResMgr.ReleaseAllResources() 'line inserted during the trial
MessageBox.Show("Template Sheet not added.")
End Try
WorksheetExists函数如下所示
Public Function WorksheetExists(ByVal WorksheetName As String) As Boolean
WorksheetExists = False
Dim Sht As Worksheet
For Each Sht In wb.Worksheets
If xlApp.Application.Proper(Sht.Name) =
xlApp.Application.Proper(WorksheetName) Then
WorksheetExists = True
Exit Function
End If
Next Sht
End Function
wb和xlApp被定义为全局变量
Dim xlApp As Excel.Application = Globals.ThisAddIn.Application
Dim wb As Excel.Workbook = Globals.ThisAddIn.Application.ActiveWorkbook
当我运行代码时,在第一次单击中它运行良好。如果删除了模板工作表,并且如果我尝试再次插入模板,则会在该行出现以下错误。
oTemplate.Worksheets.Copy(, wb.Worksheets("StartSheet"))
System.AccessViolationException HResult = 0x80004003 Message =尝试读取或写入受保护的内存。这通常表明其他内存已损坏。 来源= 堆栈跟踪:
如果我重新启动excel应用程序,则代码可以正常运行。不允许的是插入模板表并将其删除,然后在同一会话中再次插入同一模板表。我想念什么吗?