Python=3.9.6 / pywin32=301 / MS Word ver 2202 build 16.0.14931.20116
The MS document says that 'HighlightColor' can be set through Word.Font.highlighColor attribute, but I get AttributeError.
import win32com.client as win32
word = win32.gencache.EnsureDispatch("Word.application")
word.Visible = True
doc = word.Documents.Open(r"C:\Users\je\wordcolor\test.docx")
doc = word.ActiveDocument
para = doc.Paragraphs(1) # First paragraph
word.Selection.Start = para.Range.Start
word.Selection.End = para.Range.End
# Getting current highlight color
print(word.Selection.Font.highlightColor) # THIS LINE INVOKES ATTRIBUTE ERROR
# Traceback (most recent call last):
# File "C:\Users\je\wordcolor\test.py", line 13, in <module>
# print(word.Selection.Font.highlightColor)
# File "C:\Users\je\AppData\Local\Programs\Python\Python39\lib\site-packages\win32com\client\__init__.py", line 524, in __getattr__
# if d is not None: return getattr(d, attr)
# File "C:\Users\je\AppData\Local\Programs\Python\Python39\lib\site-packages\win32com\client\__init__.py", line 484, in __getattr__
# raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr))
# AttributeError: '<win32com.gen_py.Microsoft Word 16.0 Object Library._Font instance at 0x2643474563520>' object has no attribute 'highlightColor'
I also tried HighlightColor instead but was the same. It has no response if I set it.
On the other hand
There are discrepancies between the document and pywin32. For example, it says it is Font.color to get/set font color but I actually need to have Font.Color (that's why I also tried HighlightColor). Furthermore, for a color argument, an integer is required while it says a hex string should be passed. How can I notice those differences?
CodePudding user response:
Because you are using win32com
and the 'Word.Application' object, you need to refer to the Word object model, found here (not in the Javascript API reference linked in the question). In this model, the Font object does not have a HighlightColor
property, hence the attribute error.
In Word VBA, you can change the selection highlight colour by:
Selection.Range.HighlightColorIndex = wdYellow
Hence to query this value in Python:
print(word.Selection.Range.HighlightColorIndex)
and set it using:
word.Selection.Range.HighlightColorIndex = win32.constants.wdYellow
The reason I mention VBA is that the commands used in Python to control Word via win32com are pretty much identical to VBA. So one quick way to find out how to achieve something is to record a macro in VBA which does what you want, and to inspect the generated VBA code to find out the object types, properties and methods.