1

本主题与:Excel 中的多选工作表是什么对象类型?

为了概述问题,我运行了一些代码来更改我在 Excel 中的选择,并且我想将选择恢复为原来的状态(我称之为“originalSelection”)。在大多数情况下,您可以只调用 originalSelection 上的 Select() 方法。

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

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

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

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

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

我想知道是否有一种方法可以通过代码一个一个地模拟班次选择表?我发现的最接近的东西是范围分组的东西,但没有工作表。

我试图保持我的概述简短,但如果您需要更多关于我在做什么的说明,请问。

4

1 回答 1

4

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

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

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(); 
于 2012-05-16T18:24:26.300 回答