我正在为Excel工作表创建VSTO解决方案,该工作表的namedRange包含16行和3列(总共48个单元格)。当这些单元格之一被更改时,我需要对所有48个单元格进行迭代以进行一些计算。 我尝试将Change事件添加到namedRange,但是问题是这仅允许我访问当前更改的单元格。当其中一个被更改时,是否有可能迭代namedRange的所有单元格?
谢谢大卫
答案 0 :(得分:0)
这可以通过SheetChange事件,一些条件逻辑和命名范围内的枚举数来实现。
为了清楚起见,我添加了评论。希望这会有所帮助。
已更新: 包括检查以确保CHANGED单元格位于NAMED RANGE之内。这样,如果工作表上的单元格被更改但不在“命名范围”内(以某些条件逻辑为代价),它将避免不必要的处理。
//must be declared in scope
Range myNamedRange;
private void SetupEventHandlerForRange(Workbook wb, String namedRange)
{
//get the Range object of the namedRange
myNamedRange = wb.Worksheets.GetRangeByName(namedRange);
//subscribe to the SheetChange event
this.SheetChange += new
Excel.WorkbookEvents_SheetChangeEventHandler(
CheckNamedRangeOnCellChange);
}
void CheckNamedRangeOnCellChange(object Sh, Excel.Range Target)
{
//get the Worksheet object
Excel.Worksheet sheet = (Excel.Worksheet)Sh;
//check if worksheet is the desired sheet name (optional)
if(sheet.Name == "The Name Of The Sheet You Want To Check")
{
//will stay false until it finds a cell in range
bool cellInRange = false;
//get the range enumerator for the ALTERED range
IEnumerator altRangeEnum = Target.GetEnumerator();
while (altRangeEnum.MoveNext())
{
//get the cell object and check if it is in the namedRange
Cell cell = (Cell)altRangeEnum.Current;
cellInRange = IsCellIsInRange(cell, myNamedRange);
//if the cell is in the namedRange break
//we want to continue if any of the cells altered are in
//the namedRange
if(cellInRange) break;
}
//changed cell is not in namedRange, return
if(!cellInRange) return;
//get the range enumerator
IEnumerator rangeEnum = myNamedRange.GetEnumerator();
while (rangeEnum.MoveNext())
{
Cell cell = (Cell)rangeEnum.Current;
//do something with cell
}
}
}
public bool IsCellInRange(Cell cell, Range range)
{
if (cell.Row < range.Row ||
cell.Row > range.Column ||
cell.Column < range.Row + range.Rows.Count - 1 ||
cell.Column > range.Column + range.Columns.Count - 1)
{
//cell is outside the range we want to check
return false;
}
else
{
return true;
}
}