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

如何使用xlwings获取Excel ListBox控件的选中值列表?

解决xlwings获取Excel ListBox选中项的问题

问题原因

你遇到的com_error是因为工作表Shapes中的表单控件ListBox,其ControlFormat对象的属性/方法调用逻辑和你写的不一致——部分属性是ActiveX控件专属,而表单控件的方法参数起始索引也有特殊要求。

可行解决方案

方法1:获取单个选中项(单选场景)

表单控件ListBox的选中项索引存在ListIndex属性中(未选中时返回-1),再通过List方法传入索引获取对应值,注意**List方法的参数从1开始**:

import xlwings as xw

sheet = xw.sheets.active
listbox = sheet.api.Shapes('ListBox11').ControlFormat

selected_index = listbox.ListIndex
if selected_index != -1:
    # 转换为1起始索引传入List方法
    selected_value = listbox.List(selected_index + 1)
    print(f"选中项:{selected_value}")
else:
    print("未选中任何项")

方法2:获取所有选中项(多选场景)

如果ListBox允许多选,可通过Selected方法(参数同样从1开始)遍历所有选项,筛选出选中项:

import xlwings as xw

sheet = xw.sheets.active
listbox = sheet.api.Shapes('ListBox11').ControlFormat
item_count = listbox.ListCount

selected_values = []
for i in range(1, item_count + 1):
    if listbox.Selected(i):
        selected_values.append(listbox.List(i))

print(f"所有选中项:{selected_values}")

关键注意点

  • SelectedValue是ActiveX控件的专属属性,不适用于工作表Shapes中的表单控件,直接调用会报错。
  • 表单控件ControlFormat的List、Selected方法参数均为1起始索引,而非你之前使用的0,这是触发报错的核心原因。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 21:15:34