gpt4 book ai didi

c# - 从另一个工作表中检测依赖单元格

转载 作者:行者123 更新时间:2023-12-04 22:08:13 28 4
gpt4 key购买 nike

这是说明我的问题的简化示例。
我在单元格 A1 公式中的 sheet1 中有:

sheet1!A1 cell has formula '=sheet2!C1'
sheet2!B1 cell has formula '=C1'

当 sheet2 中的单元格 C1 发生更改时,我想检测所有相关单元格,这意味着 sheet2 中的单元格 B1 和 sheet1 中的单元格 A1。但是 range.Dependents 只返回事件工作表中的单元格。我只得到单元格B1。
在 Range interop API 文档中指出,依赖项将仅返回事件工作表中的范围。
有谁知道如何从所有工作表、其他 API 调用或其他方法中检测所有依赖项?

最佳答案

这将是一个很长的代码示例,但基本上您只需要按照箭头进行操作(我假设您使用的是 C#,因为您没有指定用于互操作的语言)。

下面示例的输出是(Sheet1 上有两个单元格来演示如何遍历所有远程引用):

    Sheet1!A1    Sheet1!A2    Sheet2!B1

Health warning. This sample doesn't do any interop cleanup or app closing - this is for demonstration only

Edit Use Application.ScreenUpdating to prevent screen flicker during the tracing function.

using xl = Microsoft.Office.Interop.Excel;
// use in a console app
class Program
{
static void Main(string[] args)
{
xl.Application app = new xl.Application();
app.Visible = true;
xl.Workbook wb = app.Workbooks.Add();
xl.Worksheet worksheet1 = wb.Sheets[1];
xl.Worksheet worksheet2 = wb.Sheets[2];
xl.Range rngS1A1 = worksheet1.Range["A1"];
xl.Range rngS1A2 = worksheet1.Range["A2"];
xl.Range rngS2B1 = worksheet2.Range["B1"];
xl.Range rngS2C1 = worksheet2.Range["C1"];

rngS1A1.Formula = @"=sheet2!C1";
rngS1A2.Formula = @"=sheet2!C1";
((xl._Worksheet)worksheet2).Activate();
rngS2B1.Formula = @"=C1";

List<string> dependentAddresses = ListDependents(rngS2C1);

foreach (string address in dependentAddresses)
{
Console.WriteLine(address);
}
Console.WriteLine("done, press enter to exit");
Console.ReadLine();
}

private static List<string> ListDependents(xl.Range sourceRange)
{
sourceRange.ShowDependents(false);
string sourceAddress = sourceRange.Worksheet.Name + "!" + sourceRange.Address;
int arrowNumber = 1;
List<string> dependentAddresses = new List<string>();
do
{
string targetAddress = null;
int linkNumber = 1;
do
{
try
{
xl.Range target = sourceRange.NavigateArrow(TowardPrecedent: false, ArrowNumber: arrowNumber, LinkNumber: linkNumber++);
targetAddress = target.Worksheet.Name + "!" + target.Address;

if (sourceAddress == targetAddress) break;

dependentAddresses.Add(targetAddress);
}
catch (COMException cex)
{
if (cex.Message == "NavigateArrow method of Range class failed")
{
break;
}
throw;
}
} while (true);
if (sourceAddress == targetAddress) break;
arrowNumber++;
} while (true);

sourceRange.Worksheet.ClearArrows();
return dependentAddresses;
}
}

关于c# - 从另一个工作表中检测依赖单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16057678/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com