我需要使用PyWIn32来访问Characters对象,就像在VBA中一样:
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:
TypeError: 'Characters' object is not callable
如果我尝试循环访问“字符”对象,则返回该对象不支持枚举。
例:
for char in cell.Characters:
print(char)
我收到另一个TypeError异常:
TypeError: This object does not support enumeration
最后,如果我尝试对对象使用索引,那么我还会收到另一个TypeError:
cell.Characters[1]
我收到TypeError:
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
关于python - PyWin32 Excel单元格字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51968724/