我需要使用 PyWIn32 以与在 VBA 中类似的方式访问 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)
它返回一个类型错误:
TypeError: 'Characters' object is not callable
如果我尝试在对象 Characters 中循环,它会返回该对象不支持枚举。
例子:
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,但没有一个起作用,或者出现错误。
#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
