I'm trying to execute a macro in a Word file using Python and the pywin32 module.
My Python script opens the Word file, creates a new VBA module in the project, and tries to execute the macro from the NewMacros.bas file.
When executing the script, various errors occur, such as "Compile error: Syntax error", "Run-time error '4198'", etc.
I checked the macro file for syntax errors, installed the latest version of pywin32 and checked permissions to execute macros.
Here is my Python script code and the contents of the NewMacros.bas macro file:
VBA code:
Sub IterateThroughPictures()
Dim shp As inlineShape
' Перебираем все встроенные фотографии и рисунки в документе
For Each shp In ActiveDocument.InlineShapes
If shp.Type = wdInlineShapePicture Then
' Выделяем текущую фотографию или рисунок
shp.Select
' Выполняем код для текущей фотографии или рисунка
Selection.InsertCaption Label:="Рисунок", TitleAutoText:="InsertCaption2", _
Title:="", Position:=wdCaptionPositionBelow, ExcludeLabel:=0
' Редактируем название фотографии
With shp.Range
.Font.Size = 12
.Font.Color = RGB(0, 0, 0) ' Черный цвет
.Font.Name = "Times New Roman"
.ParagraphFormat.Alignment = wdAlignParagraphCenter
End With
' Снимаем выделение с фотографии или рисунка
Selection.Collapse Direction:=wdCollapseEnd
End If
Next shp
End Sub
Python Script:
import win32com.client
import time
# Создаем объект приложения Word
word = win32com.client.Dispatch("Word.Application")
# Открываем документ
time.sleep(2) # Задержка в 2 секунды
doc = word.Documents.Open(r"C:\Users\felix\Downloads\test\111.docx")
# Получаем объект VBProject, представляющий проект VBA в документе
vb_project = doc.VBProject
# Создаем новый модуль в проекте VBA
module = vb_project.VBComponents.Add(1)
# Устанавливаем имя модуля
module.Name = "NewMacros"
# Загружаем содержимое макроса из файла NewMacros.bas
with open('NewMacros.bas', 'r') as f:
code = f.read()
# Записываем код макроса в модуль
module.CodeModule.AddFromString(code)
# Выполняем макрос
word.Application.Run("NewMacros.ApplyStyleToCaptions")
word.Application.Run("NewMacros.IterateThroughPictures")
# Save and close the document
doc.Save()
doc.Close()
# Close the Word application
word.Quit()
I run the script:
python .\test.py
On the first run, an error occurs:
Traceback (most recent call last):
File "C:\Users\felix\Downloads\test\test.py", line 28, in <module>
word.Application.Run("NewMacros.ApplyStyleToCaptions")
File "<COMObject <unknown>>", line 8, in Run
File "C:\Users\felix\AppData\Roaming\Python\Python311\site-packages\win32com\client\dynamic.py", line 366, in _ApplyTypes_
result = self._oleobj_.InvokeTypes(
^^^^^^^^^^^^^^^^^^^^^^^^^^
pywintypes.com_error: (-2147352567, 'Ошибка.', (0, 'Microsoft Word', 'Не удалось запустить указанный макрос', 'wdmain11.chm', 37401, -2147352573), None)
On the second run, a Word file opens, no changes occur in it, but another error appears:
Traceback (most recent call last):
File "C:\Users\felix\Downloads\test\test.py", line 18, in <module>
module.Name = "NewMacros"
^^^^^^^^^^^
File "C:\Users\felix\AppData\Roaming\Python\Python311\site-packages\win32com\client\dynamic.py", line 685, in __setattr__
self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
pywintypes.com_error: (-2147352567, 'Ошибка.', (0, None, None, None, 0, -2146795475), None)
Version python 3.11.1