PyWin32 Excel 单元格字符

PyWin32 Excel Cell Characters

我需要以与 VBA:

类似的方式使用 PyWIn32 访问 Characters 对象
Sub print_characters_cell()
    dim idx as Long
    For idx= 1 To activeSheet.cells("A1").Characters.Count
        debug.print(cell.Characters(idx, 1))
    Next idx
End Sub

然而,当我尝试使用 Python 中的对象并尝试以类似方式访问 VBA 中的单个字符时,我收到以下消息:

如果我尝试单独访问一个角色

cell = ActiveSheet.Cells(1,1)
cell.Characters(1)

它 returns 类型错误:

TypeError: 'Characters' object is not callable

如果我尝试在对象字符中循环它returns该对象不支持枚举。

示例:

for char in cell.Characters:
    print(char)

我得到另一个 TypeError 异常:

TypeError: This object does not support enumeration

最后,如果我尝试对对象使用索引,我还会得到另一个 TypeError:

cell.Characters[1]

我收到类型错误:

TypeError: 'Characters' object does not support indexing

编辑:添加一些允许按照建议对其进行测试的代码。

from win32com.client import Dispatch
xl = Dispatch('excel.application')
wb = xl.Workbooks.Add()
sh = wb.ActiveSheet
cl = sh.Cells(1,1)
cl.Value = 'Some characters to check'
dir(cl.Characters)

而且我必须使用上面提到的 cl.Characters,但是 none 有效,或者出现错误。

#TypeError
for char in cl.Characters:
    print(char.Text)
#TypeError
cl.Characters(1,1)
#TypeError
cl.Characters[1]

那么,我如何单独处理 Python 中的字符?

根据 this answer,您需要使用 .GetCharacters 而不是 .Characters

cell.GetCharacters(1,1).Text