在Excel.Application的不同实例之间复制工作表

问题描述 投票:1回答:2

我正在使用VSTO Excel加载项,在某个时候,它将从资源中打开模板工作簿,并将工作表从其中复制到运行中的Excel实例。从模板复制时,我想避免白色的短窗口闪烁,因此我创建了一个Excel.Application的隐藏实例,然后从那里调用它。这部分有效,但是在复制时,我不断收到“ System.Runtime.InteropServices.COMException:'工作表类的复制方法失败'“

Dim tempFileName As String = "DesignWorks1_Template"
Dim tempName As String = Path.GetTempPath() & "\" & tempFileName & ".xlsx"
Dim ResMgr = New Resources.ResourceManager("MyUtilities.Resources", System.Reflection.Assembly.GetExecutingAssembly)
Dim fstream As New FileStream(tempName, FileMode.Create, FileAccess.Write)
Dim filestreamWrite As New BinaryWriter(fstream)
filestreamWrite.Write(My.Resources.DesignWorks1, 0, My.Resources.DesignWorks1.Length)
fstream.Close()
filestreamWrite.Close()

Dim currentWorkbook As Excel.Workbook = Globals.ThisAddIn.Application.ActiveWorkbook
Dim newHiddenApp As New Excel.Application
newHiddenApp.Visible = False
Dim oTemplate As Excel.Workbook = newHiddenApp.Workbooks.Add(tempName)
oTemplate.Worksheets(compareName).Copy(currentWorkbook.Worksheets(1)) 'error here
oTemplate.Close()
My.Computer.FileSystem.DeleteFile(tempName)
ResMgr.ReleaseAllResources()

提前感谢。

excel vb.net vsto
2个回答
0
投票

是否可以从模板中指定特定的图纸?我尝试了Sheets.Add,但它似乎是从指定路径导入所有工作表。 –虚拟下划线

这是将工作簿中的每个工作表导出到WorkSheet模板文件的主要痛点。当您执行另存为工作表模板时,主题工作表必须是工作簿中唯一的工作表。如果工作簿中存在多个工作表,则将导出工作簿模板。

您可以将以下VBA代码复制到要从中导出模板的工作簿的ThisWorkbook代码文件中。确保修改代码中的templateFolder = "F:\Temp\Templates"行。运行它,它将导出工作簿中的每个工作表。

Sub ExportWorksheetTemplates()
   Excel.Application.DisplayAlerts = False
   Excel.Application.ScreenUpdating = False

   Dim templateFolder As String
   templateFolder = "F:\Temp\Templates"   ' set this to an existing folder on you system

   Dim tmpWb As Excel.Workbook
   Dim old_numsheets As Integer

   old_numsheets = Excel.Application.SheetsInNewWorkbook
   Excel.Application.SheetsInNewWorkbook = 1

   Dim ws As Excel.Worksheet
   Dim newWBFirstSheet As Excel.Worksheet

   Dim templatePath As String

   On Error GoTo Finalize

   For Each ws In ThisWorkbook.Worksheets
      Set tmpWb = Excel.Application.Workbooks.Add()
      Set newWBFirstSheet = tmpWb.Worksheets(1)
      newWBFirstSheet.Name = "."
      ws.Copy after:=newWBFirstSheet
      newWBFirstSheet.Delete


      templatePath = templateFolder & "\" & tmpWb.Worksheets(1).Name & ".xltx"
      tmpWb.Worksheets(1).SaveAs templatePath, Excel.XlFileFormat.xlOpenXMLTemplate

      tmpWb.Close
   Next

Finalize:
   Excel.Application.DisplayAlerts = True
   Excel.Application.ScreenUpdating = True
   Excel.Application.SheetsInNewWorkbook = old_numsheets
End Sub

现在您可以将每个文件添加到VSTO项目的资源中。

然后,您将按照当前操作将资源模板导出到一个临时文件。

当您使用Sheets.Add method并指定Type:="path to template"时,您现在只会将单个工作表添加到工作簿中。


0
投票

[在桌面上运行Excel时,您无法在实例之间复制工作表。因此,我怀疑用VB启动Excel实例时是否可以做到这一点。

为了在工作簿之间复制工作表,这些工作表需要在同一实例中运行。

© www.soinside.com 2019 - 2024. All rights reserved.