VSTO Excel - 如何创建具有多个区域的范围

时间:2022-11-07 20:26:33

If I have one or more ranges how can I combine them into a range with multiple areas?

如果我有一个或多个范围,我如何将它们组合成一个具有多个区域的范围?

One might think to do it like this... but this won't even compile...

人们可能会认为这样做......但这甚至不会编译......

Excel.Worksheet sheet = workbook.ActiveSheet;
Excel.Range rng1 = (Excel.Range) sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[3,42]);
Excel.Range rng2 = (Excel.Range) sheet.get_Range(sheet.Cells[5, 1], sheet.Cells[6,42]);
Excel.Range result = new Excel.Range();
result.Areas.Add(rng1);
result.Areas.Add(rng2);

UPDATE:

更新:

This is not a duplicate... this is about creating a range with two Areas... not about creating a range from two ranges each with a single cell (which would result in a range with only one area)

这不是重复...这是关于创建一个具有两个区域的范围...不是关于从两个范围创建范围,每个范围都有一个单元格(这将导致只有一个区域的范围)

1 个解决方案

#1


0  

Derived from one of the answers in the above referred to "duplicate" question.

源自上面提到的“重复”问题中的一个答案。

Note: it seems if the areas can be combined a Union will do this (for example, two adjacent rows) but if they cannot be combined like this then it creates multiple areas. (not 100% sure on this)

注意:似乎区域可以组合,联盟将执行此操作(例如,两个相邻的行),但如果它们不能像这样组合,那么它会创建多个区域。 (不是100%肯定)

Also, Union can have more than two parameters... e.g. Union(range1, range2, range3, etc...)

此外,Union可以有两个以上的参数......例如联盟(范围1,范围2,范围3等...)

var excelApp = Globals.ThisAddIn.Application as Excel.Application;
var sheet = workbook.ActiveSheet as Excel.Worksheet;
var range1 = sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[3,42]) as Excel.Range;
var range2 = sheet.get_Range(sheet.Cells[5, 1], sheet.Cells[6,42]) as Excel.Range;
var result = excelApp.Union(range1, range2) as Excel.Range;

#1


0  

Derived from one of the answers in the above referred to "duplicate" question.

源自上面提到的“重复”问题中的一个答案。

Note: it seems if the areas can be combined a Union will do this (for example, two adjacent rows) but if they cannot be combined like this then it creates multiple areas. (not 100% sure on this)

注意:似乎区域可以组合,联盟将执行此操作(例如,两个相邻的行),但如果它们不能像这样组合,那么它会创建多个区域。 (不是100%肯定)

Also, Union can have more than two parameters... e.g. Union(range1, range2, range3, etc...)

此外,Union可以有两个以上的参数......例如联盟(范围1,范围2,范围3等...)

var excelApp = Globals.ThisAddIn.Application as Excel.Application;
var sheet = workbook.ActiveSheet as Excel.Worksheet;
var range1 = sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[3,42]) as Excel.Range;
var range2 = sheet.get_Range(sheet.Cells[5, 1], sheet.Cells[6,42]) as Excel.Range;
var result = excelApp.Union(range1, range2) as Excel.Range;