当前位置: 动力学知识库 > 问答 > 编程问答 >

C#: Excel: set selected workseet for next workbook-opening

问题描述:

I want to select a worksheet that should be the selected worksheet when I open the workbook the next time. I've already tried the ".Activate()" and the ".Select()" method of the worksheet but it doesn't work.

How can I do this with the Excel interop assembly in C#?

Regards

Matthias

网友答案:

I'm assuming that you want to select the sheet from inside of an Excel COM-addin.

First you need a place to store the name of the Worksheet that needs to be selected. A possible place that's not directly visible to the user is in Workbook.CustomDocumentProperties.

Second you need to read this DocumentProperty the next time and activate the Worksheet when the Workbook is opened. This can be done in the void OnStartupComplete(ref Array custom) if there is already an _application.ActiveWorkbook and additionally in the EventHandler of _application.WorkbookOpen += wb => { ... }; if Excel is already running.

(_application.WorkbookOpen is not always called when you open a Workbook without Excel already running, so you have to activate it in the OnStartupComplete too.)

To effectively select the sheet you have to call Workbook.Activate() first and then call Worksheet.Activate(). If you don't activate the Workbook before the Worksheet it won't work most of the time. Additionally it could be useful to select the first cell of the sheet calling ws.Cells[1, 1].Select().

If you are inside a COM-addin then you get the _application from the first parameter of void OnConnection(object application, ...). You just need to cast it to _application = application as Application;.

If you are inside a VSTO-addin you can get the Application from Globals.ThisWorkbook.Application.

The only drawback (that I know of) is: You can't select a sheet if you are in an Excel-addin (not a COM-addin) that only exports UDFs to Excel because this type of addin has no permission to do so.

分享给朋友:
您可能感兴趣的文章:
随机阅读: