【问题标题】:How to programmatically group (shift select) sheets in Excel如何在 Excel 中以编程方式对工作表进行分组(移位选择)
【发布时间】:2023-04-02 14:37:01
【问题描述】:

本话题涉及: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 默认的)。但是,如果您选择了多个工作表,则在尝试再次调用 Select 时可能会遇到错误。你需要跳来跳去才能让事情顺利进行。

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

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

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

我想知道是否有一种方法可以通过代码务实地模拟换档选择表?我找到的最接近的东西是范围分组的东西,但没有工作表。

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

【问题讨论】:

  • 你不能选择组之前激活工作表吗?
  • 不,它将活动工作表更改为排序中的第一张工作表(多么方便,对吧?)。而且,如果您使用 range.Select() 跟进 Sheets.Select() 如果该范围不在该活动工作表上,则会引发错误。这就是为什么我会在这些电话之间进行活动。

标签: c# excel


【解决方案1】:

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

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

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(); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    • 2013-03-16
    • 1970-01-01
    相关资源
    最近更新 更多