这是说明我的问题的简化示例。 我在我的sheet1中的单元格A1公式:
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文档中声明,dependents将仅返回活动工作表的范围。 有没有人知道如何从所有工作表,一些其他API调用或其他方法中检测所有依赖项?
答案 0 :(得分:2)
这将是一个很长的代码示例,但基本上您只需要遵循箭头(我假设您使用的是C#,因为您没有指定用于互操作的语言)。< / p>
下面示例的输出是(Sheet1上有两个单元格来演示如何遍历所有远程引用):
Sheet1!A1 Sheet1!A2 Sheet2!B1
健康警告。此示例不执行任何互操作清理或应用程序关闭 - 这仅用于演示
修改使用Application.ScreenUpdating
可防止在跟踪功能期间屏幕闪烁。
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;
}
}