You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用UI Automation设置Excel单元格值失败的问题求助

问题描述
  • 通过UI Automation可以正常获取Excel单元格的所有信息,但调用ValuePattern.SetValue()方法设置值时,代码执行无报错,单元格值却未实际更新
  • 使用Microsoft Accessibility Insights工具测试编辑操作,工具提示执行成功,但单元格值依然没有变化
  • 已尝试以管理员身份启动Excel,问题仍未解决

使用Accessibility Insights更新值

相关代码
AutomationElement root = AutomationElement.RootElement;

var excelRoot = FindInTree(
            TreeWalker.ControlViewWalker.GetFirstChild(root),
            "WorkInstructionExcel.xlsx"
        );
Condition conditions = new AndCondition(
            new PropertyCondition(AutomationElement.IsEnabledProperty, true),
            new PropertyCondition(AutomationElement.ControlTypeProperty,
                ControlType.DataItem)
        );

AutomationElementCollection gridCollection =
            excelRoot.FindAll(TreeScope.Descendants, conditions);

var enumerator = gridCollection.GetEnumerator();

AutomationElement elem;
        
while (enumerator.MoveNext())
{
     elem = (AutomationElement)enumerator.Current;
     if (elem.Current.Name == "C2")
     {
        if (elem.TryGetCurrentPattern(ValuePattern.Pattern, out object valuePattern))
           if (((ValuePattern)valuePattern).Current.IsReadOnly == false)
                    {
                        elem.SetFocus();
                       
                        ((ValuePattern)valuePattern).SetValue("test");
                    }
            }
        }
可行解决方案
  • 触发单元格进入编辑模式:Excel的DataItem元素直接调用SetValue可能不生效,需先模拟F2按键进入编辑状态,再执行设置操作。可在elem.SetFocus()后添加:

    // 使用InputSimulator模拟F2进入编辑(需引入InputSimulator库)
    InputSimulator sim = new InputSimulator();
    sim.Keyboard.KeyPress(VirtualKeyCode.F2);
    // 再执行SetValue操作
    
  • 改用RawViewWalker查找元素:ControlViewWalker可能过滤了部分底层交互元素,替换为RawViewWalker重新定位Excel窗口:

    var excelRoot = FindInTree(
        TreeWalker.RawViewWalker.GetFirstChild(root),
        "WorkInstructionExcel.xlsx"
    );
    
  • 定位单元格内部的编辑控件:进入编辑状态后,单元格会生成一个ControlType.Edit类型的子控件,找到该控件再调用SetValue:

    elem.SetFocus();
    // 模拟F2进入编辑
    SendKeys.SendWait("{F2}");
    // 查找内部编辑框控件
    Condition editCondition = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit);
    AutomationElement editElem = elem.FindFirst(TreeScope.Children, editCondition);
    if (editElem != null && editElem.TryGetCurrentPattern(ValuePattern.Pattern, out object editPattern))
    {
        ((ValuePattern)editPattern).SetValue("test");
        SendKeys.SendWait("{ENTER}");
    }
    

内容的提问来源于stack exchange,提问作者Cam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 11:31:06