Python调用Word宏批量合并docx文件时触发(-2147352567)异常的问题求助
Python调用Word宏批量合并docx文件时触发(-2147352567)异常的问题求助
我现在用Python自动化一个合并多个docx文件的项目,这个宏在Word里运行完全正常,但用Python代码调用时却触发了错误。
错误提示如下:
An error occurred: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147352573), None)
我的VBA代码如下:
Sub ConcatenateDocxFiles() Dim wordApp As Word.Application Dim outputDoc As Word.Document Dim inputDoc As Word.Document Dim folderPath As String Dim fileName As String Dim filePath As String Dim insertedText As Range ' Set the folder path containing the .docx files folderPath = "Fiches\" ' Initialize Word application On Error Resume Next Set wordApp = GetObject(, "Word.Application") If Err.Number <> 0 Then Set wordApp = CreateObject("Word.Application") End If On Error GoTo 0 wordApp.Visible = False ' Keep Word hidden during the process ' Create a new Word document for concatenation Set outputDoc = wordApp.Documents.Add ' Loop through all .docx files in the folder fileName = Dir(folderPath & "*.docx") Do While fileName <> "" filePath = folderPath & fileName ' Full file path ' Open the .docx file in Word (use positional arguments) Set inputDoc = wordApp.Documents.Open(filePath, False, True) ' ReadOnly = True (position 3) ' Insert "______Begin of filename______" at the start of each file Set insertedText = inputDoc.Content insertedText.InsertBefore "______Begin of " & fileName & "______" & vbCrLf ' Add filename header insertedText.Collapse Direction:=wdCollapseEnd ' Insert "______End of filename______" at the end of each file's content insertedText.InsertAfter vbCrLf & "______End of " & fileName & "______" & vbCrLf ' Add filename footer insertedText.Collapse Direction:=wdCollapseEnd ' Copy content from the .docx file inputDoc.Content.Copy ' Paste content into the output document outputDoc.Content.Paste inputDoc.Close False ' Close the input document fileName = Dir ' Get the next file Loop For Each para In outputDoc.Paragraphs If InStr(para.Range.Text, "______Begin of") > 0 Or InStr(para.Range.Text, "______End of") > 0 Then para.Range.Font.Size = 6 ' Set font size to 6 para.Range.Style = "Normal" ' Set the style to "Normal" para.Alignment = wdAlignParagraphCenter End If Next para ' Save the concatenated document outputDoc.SaveAs2 folderPath & "MergedDocument.docx", FileFormat:=wdFormatDocumentDefault outputDoc.Close ' Clean up wordApp.Quit Set wordApp = Nothing MsgBox "All .docx files have been concatenated into 'MergedDocument.docx' in the folder.", vbInformation End Sub
我使用的Python代码如下:
import win32com.client as win32 import os def run_macro(): docm_file_path = "Concat.docm" macro_name = "Concat.docm!Module1.ConcatenateDocxFiles" try: if not os.path.exists(docm_file_path): print(f"Error: The file '{docm_file_path}' does not exist.") return #Kill all wordapp os.system("taskkill /f /im WINWORD.EXE") # Initialize Word application word_app = win32.Dispatch("Word.Application") word_app.Visible = False doc = word_app.Documents.Open(os.path.abspath(docm_file_path), ReadOnly = 1) word_app.Application.Run(f"{macro_name}") doc.Close(SaveChanges=False) word_app.Quit() del word_app print(f"Macro '{macro_name}' executed successfully in '{docm_file_path}'.") except Exception as e: print(f"An error occurred: {e}") run_macro()
备注:内容来源于stack exchange,提问作者JAFF-cYberThieF
相关产品推荐
相关产品推荐

