Thanks a lot!
Originally Posted by
macropod
bearing in mind the need to use either \\ or / as the path separators in path_xlsx and that both path_xlsx and ref_xlsx must include double quotes at each end.
Especially this did the trick. It was a little difficult to persuade python to parse explicit double backslash as argument.
As I was struggeling with this for a while, I'll leave my final macro here:
Sub AutoOpen()
Word.Options.UpdateLinksAtOpen = False
End Sub
Sub UpdateLinks(path_docx, path_xlsx)
Documents(path_docx).Activate
With ActiveDocument
For Each fld In .Fields
With fld
If .Type = wdFieldLink Then
.Code.Text = Replace(.Code.Text, "PATH", path_xlsx)
.Update
End If
End With
Next
.Fields.Unlink
End With
End Sub
The dummy links look like:
{ LINK Excel.Sheet.12 "PATH" "MySheetName!R1C1:R17C6" \a \f 4 \h}
The Python code running the macro:
import win32com.client as win32
word = win32.Dispatch('Word.Application')
# run macro
wordDoc = word.Documents.Open(path, False, False, False)
word_path = word_path.replace("/", "\\") # for some reason vba expects different
excel_path = excel_path.replace("/", "\\\\") # backslashes for .Activate and in FieldLinks
word.Run("UpdateLinks", word_path, excel_path)
# save doc
wordDoc.SaveAs2(path, FileFormat=16)
wordDoc.Close()
word.Quit()