Reputation: 33
I insert an OLE object in a Word document using the VBA code below.
Sub Test()
Selection.InlineShapes.AddOLEObject ClassType:="Excel.Sheet.12", FileName _
:="C:\Users\ananyroy\Documents\SDWAN\NRFUAutomation\Trials\TestFile.xlsx", LinkToFile _
:=False, DisplayAsIcon:=True, IconFileName:= _
"C:\WINDOWS\Installer\{90140000-0011-0000-0000-0000000FF1CE}\xlicons.exe" _
, IconIndex:=100, IconLabel:="Book1.xlsx", Range:=ActiveDocument.Paragraphs(4).Range
End Sub
I am looking for a method to add this OLE object after a particular string or in place of the placeholder string.
The Range parameter seems a tedious way to achieve it.
Upvotes: 0
Views: 864
Reputation: 311
Came across this post today. I wish to achieve similar result using Python. And here's the code (syntax) I wish to share here after numerous trials and errors. ðŸ˜ðŸ˜ðŸ˜
This Python code snippet mimics the behavior of the VBA Macro discussed in the thread. The `win32com` library in Python allows manipulation of Word documents similar to Word VBA.
# Insert text file as an object in the first table (Cell Position: Third Row, Fourth Column)
table = doc.tables[0]
cell = table.Cell(3, 4)
# Get existing InlineShapes count in the cell
existing_shapes_count = cell.Range.InlineShapes.Count
# Define the current range
range_to_move = cell.Range.InlineShapes(existing_shapes_count).Range
range_to_move.Collapse(0) # Move to the end of the line
range_to_move.InlineShapes.AddOLEObject(
ClassType="Package",
FileName=os.path.abspath(text_file),
DisplayAsIcon=True
)
Hope this helps someone facing a similar challenge in the future!
Upvotes: 0
Reputation: 1713
Try this:
Sub Test()
Dim rng As Word.Range
Set rng = ActiveDocument.Content
With rng.Find
.ClearFormatting
.Forward = True
.Text = "Placeholder Text"
.Wrap = wdFindStop
.Execute
If .found Then
rng.InlineShapes.AddOLEObject ClassType:="Excel.Sheet.12", FileName _
:="C:\Users\ananyroy\Documents\SDWAN\NRFUAutomation\Trials\TestFile.xlsx", LinkToFile _
:=False, DisplayAsIcon:=True, IconFileName:= _
"C:\WINDOWS\Installer\{90140000-0011-0000-0000-0000000FF1CE}\xlicons.exe" _
, IconIndex:=100, IconLabel:="Book1.xlsx", Range:=rng
End If
End With
End Sub
Upvotes: 2