如何在Excel中用python win32com更改单元格内单个字符的颜色?

2 投票
1 回答
3291 浏览
提问于 2025-04-16 23:51

我有一个关于win32com和Excel的绑定的问题。我设置了早期绑定,并参考了O'Reilly出版的《Python Programming on Win32》这本书中的一些例子。

下面的代码运行得很好:

book2.xlApp.Worksheets('Sheet1').Cells(1,1).Font.ColorIndex = 1
book2.xlApp.Worksheets('Sheet1').Cells(1,1).Font.ColorIndex = 2

这段代码根据数字改变了整个单元格的字体颜色。不过,下面这段代码就不行:

book2.xlApp.Worksheets('Sheet1').Cells(1,1).Characters(start,length).Font.ColorIndex = 1

我得到了以下的回调信息:

Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: Characters instance has no __call__ method

但是在Excel的VBA中,这段代码是可以工作的。有没有人能告诉我解决办法?我真的需要在Excel单元格中更改字符串的部分内容。

非常感谢。

1 个回答

6

使用 GetCharacters:

Cells(1,1).GetCharacters(start,length).Font.ColorIndex = 1

撰写回答