PDA

View Full Version : [SOLVED:] Adding a picture to a Shape



Roderick
10-17-2017, 04:39 AM
I'm using Word 2016.

Here's what I'm trying to do: In a document I have a Shape ("myShape"). I now want to add a picture to that Shape and to do it manually, I select it then go to Format (Drawing Tools)>Shape Fill>Picture... and from the Insert File dialog box I select an appropriate picture and it inserts it OK. No problems!

Then I thought I'd like to see whether the Macro recorder would record those steps. I tried it but all it would record was:

ActiveDocument.Shapes.Range(Array("myShape")).Select

Then I decided to research what others might have done and cobbled together a procedure:

Sub InsertPictureDialog()
Dim oDialog As Word.Dialog
Dim strName As String

'Get a handle to the Insert picture dialog
Set oDialog = Dialogs(wdDialogInsertPicture)

' Work with dialog
With oDialog
' Display the dialog
.Display

'Insert Shape Picture if the Name property (Filepath) <> ""
If .Name <> "" Then
strName = ActiveDocument.FullName
ActiveDocument.Shapes.Range(Array("myShape")).Select

With ActiveDocument.Shapes("myShape").Fill
.Visible = msoTrue
.UserPicture strName
End With
End If
End With

' Clean up
Set oDialog = Nothing
End Sub

Did it work? No, not quite. It tried to do something and it seemed to insert a picture but it came out as "The picture can't be displayed"

I've fooled around with changing the code here and there but with no luck.

I'm sure there must be an obvious mistake but cannot spot it.

Any thoughts, please?

SamT
10-18-2017, 06:19 AM
bump

mdmackillop
10-18-2017, 07:50 AM
Sub test()
FileName = "C:\Users\mdmac\OneDrive\Pictures\bear.jpg"
With ActiveDocument.Shapes("MyShape").Fill
.Visible = msoTrue
.UserPicture FileName
End With
End Sub
'or
Sub test2()
Set dlg = Application.FileDialog(FileDialogType:=1)
dlg.Show
FileName = dlg.SelectedItems(1)
With ActiveDocument.Shapes("MyShape").Fill
.Visible = msoTrue
.UserPicture FileName
End With
End Sub

Paul_Hossler
10-18-2017, 08:04 AM
I think you were passing the wrong file name to .UserPicture





Option Explicit
Sub InsertPictureDialog()
Dim oDialog As Word.Dialog
Dim strName As String

Set oDialog = Dialogs(wdDialogInsertPicture)
With oDialog
.Display

'Insert Shape Picture if the Name property (Filepath) <> ""
If .Name <> "" Then
With ActiveDocument.Shapes("myShape").Fill
.Visible = msoTrue
.UserPicture oDialog.Name ' <<<<<<<<<<<<<<<<<
End With
End If
End With

' Clean up
Set oDialog = Nothing
End Sub

Roderick
10-21-2017, 08:54 AM
Thanks again, folks for all your help.

Applied the filename as you suggested, Paul, and it works brilliantly!