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

C# 设置Word中光标所在表格行高度时循环不执行问题求解

问题原因

这是Word COM对象模型的固有设计:

  • 当选中状态为插入点(Selection.Type = wdSelectionIP,即仅点击单元格未选中任何内容)时,即使sel.Rows.Count返回1,Rows集合的枚举器也不会返回任何行对象,所以foreach循环会直接跳过。
  • 只有当选中范围是显式的区域选择(比如选中多行、选中连续多个单元格)时,Rows集合的枚举逻辑才会正常生效。
修复方案

不需要主动选中整行,可通过以下两种方式处理:

方案1:兼容原有逻辑,补充单一行场景的兜底

if (sel.Information[WdInformation.wdWithInTable])
{
    float targetHeight = InchesToPoints(height);
    if (sel.Rows.Count > 0)
    {
        try
        {
            foreach (Row current in sel.Rows)
            {
                current.Height = targetHeight;
            }
        }
        catch
        {
            // 捕获枚举失败的单单元格插入点场景
            sel.Rows[1].Height = targetHeight;
        }
    }
    else
    {
        sel.Rows[1].Height = targetHeight;
    }
}

方案2:通过单元格定位行,逻辑更稳定

该方式不依赖Rows集合的枚举行为,适配所有场景:

if (sel.Information[WdInformation.wdWithInTable])
{
    float targetHeight = InchesToPoints(height);
    // 处理选中多行的场景
    if (sel.Rows.Count > 1)
    {
        foreach (Row current in sel.Rows)
        {
            current.Height = targetHeight;
        }
    }
    else
    {
        // 直接获取插入点所在单元格对应的行
        sel.Cells[1].Row.Height = targetHeight;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:39:02