如何以编程方式在Excel中分组(切换选择)工作表

时间:2012-05-16 15:56:04

标签: c# excel

本主题与:What object type are multiple selected sheets in Excel?

有关

为了概述这个问题,我运行了一些代码来改变我在Excel中的选择,我希望将选择返回到它原来的位置(我称之为“originalSelection”)。在大多数情况下,您只需在originalSelection上调用Select()方法。

var originalSelection = ExcelApp.Selection;
originalSelection.GetType().InvokeMember("Select", System.Reflection.BindingFlags.InvokeMethod, null, originalSelection , null);

选择多个工作表后,选择类型始终是一个范围(这是Excel默认的范围)。但是,如果选择了多个工作表,则在尝试再次调用“选择”时可能会遇到错误。你需要做一些跳舞才能让事情发挥作用。

如果选择了多个工作表,而不是所有工作表,则可以执行以下操作:

selectedSheets.Select();
activeSheet.Activate();
originalSelection.Select(); //this was casted to an Excel.Range

但是,如果选择了所有工作表,activeSheet.Activate()行将取消选择所有其他选定工作表。如果您使用UI本机尝试,也会发生这种情况。

我想知道是否有办法通过代码逐个实际模仿班次选择表单?我发现的最近的东西是范围分组的东西,但没有任何表格。

我试图让我的概述简短,但如果你需要更多澄清我在做什么,那就问问。

1 个答案:

答案 0 :(得分:3)

所以我想出了一种以编程方式选择表格的方法。

您可以创建名称的字符串数组,并使用数组的顺序来获取工作表的集合。选择此集合,您应该选择所有指定的工作表。

String[] sheetsToBeSelected = {"Sheet3","Sheet1","Sheet2"}; //Note, Sheet3 is the first item in this array
excel.Workbook workbook = ExcelApp.ActiveWorkbook; //get your Excel application however you want
excel.Sheets worksheets = workbook.Worksheets; //get all the sheets in this workbook

//This gets a collection of the sheets specified and ordered by the array of names passed in. 
//Just call select on this collection, and the first sheet in the collection becomes the active sheet!
((excel.Sheets)worksheets.get_Item(sheetsToBeSelected)).Select();