issue with adding picture using image control

A

Associates

Hi,

I was trying to insert an image (jpeg or png) into a word document (not a
form though) using the Image control but was not able to find a method to do
that. I wonder if anyone might be able to share some knowledge with me.

Any help would be greatly appreciated.

Thank you in advance
 
J

Jay Freedman

Hi,

I was trying to insert an image (jpeg or png) into a word document (not a
form though) using the Image control but was not able to find a method to do
that. I wonder if anyone might be able to share some knowledge with me.

Any help would be greatly appreciated.

Thank you in advance

More information, please:

- What version of Word?
- Are you referring to the Image control on the Control Toolbox, or something
else?
- Are you trying to do this with a macro (as implied by the fact you posted in a
VBA newsgroup) or through the user interface?
- Exactly what have you tried already, and how does it fail? Error message, or
just no result?
- Why are you using an Image control rather than simply inserting the picture
into the document?
 
A

Associates

Thank you Jay for your reply.
- What version of Word? It is Word 2002
- Are you referring to the Image control on the Control Toolbox, or something
else?
Yes, I am referring to the Image control on the Control ToolBox
- Are you trying to do this with a macro (as implied by the fact you posted in a
VBA newsgroup) or through the user interface?
I have a userform that allows users to locate where the image they want to
include in their word report document by using a browse file button. After
filling out all the required fields in the form, user can then click the
button "Generate Report". What this button does is it looks for the image
specified in the file path and then insert it to the Image Control. So you
may imagine that i have the Image Control set up somewhere in the document
where the picture appears
- Exactly what have you tried already, and how does it fail? Error message, or
just no result?
What i have tried but to no avail is to look for a method that will add
picture into the Image Control. This I was not able to find. So i am not sure
if this is a possible task to do.
- Why are you using an Image control rather than simply inserting the picture
into the document?
I am creating a standard template for our company's report to be submitted
to Clients. So to do that, i use the userform that will ask all the required
fields such as report name, company (pretty much anything that need to go
into a report). On the first page of the report, i have reserved a reasonable
space for that image (for example a logo for our client's company). This logo
can be varied depending on which clients. Some clients may have their own
logo but some don't. So to be consistent, i decided that no matter whether
there is one or none, i want that image space to be there on the top part of
the first page of the report.

Hope my explanation will help you to help me work around this issue of mine

Thank you in advance
 
J

Jay Freedman

First, I'll say that there are several ways to accomplish the look you want,
and the Image control is only one of them -- and probably the least
tractable from a VBA point of view. The problem is that an Image control,
like all the items in the Control Toolbox, is an ActiveX control that has
relatively poor support in VBA. General information about these controls,
but not specifically about the Image control, is at
http://msdn2.microsoft.com/en-us/library/aa140269(office.10).aspx. Pay close
attention to the section "Appropriateness for the Task", which details a
number of possible problems.

After showing you the answer to your specific question, I'll point to a
better alternative.

Assuming that your Image control is inserted in-line with text, you first
address it as a member of the ActiveDocument.InlineShapes collection. If its
text wrapping is anything else, you get to it through the
ActiveDocument.Shapes collection. Then you should verify that the
InlineShape (or Shape) is of the expected type, and get its
..OLEFormat.Object property which represents the Image control itself. You
can set its .Picture property by calling LoadPicture with the name of the
desired picture file, adjust its sizing properties, and finally force it to
update:

Sub ChangeImgPicture()
Dim PicName As String
Dim ipic As InlineShape
Dim oOle As OLEFormat
Dim img As Image

PicName = "C:\somefolder\somepicture.jpg" ' set as needed

Set ipic = ActiveDocument.InlineShapes(1)
If ipic.Type = wdInlineShapeOLEControlObject Then
If ipic.OLEFormat.ClassType = "Forms.Image.1" Then
Set img = ipic.OLEFormat.Object
If LCase(img.Name) = "logo" Then
With img
.Picture = LoadPicture(PicName)
.AutoSize = False
.PictureSizeMode = fmPictureSizeModeZoom
End With
' force update of picture
ActiveWindow.View = wdPrintPreview
ActiveWindow.View = wdPrintView
End If
End If
End If
End Sub

I'm not sure (and I don't have any way to test right now) whether the image
data is stored in the document file -- so that the picture will be visible
if you send the document to another computer that doesn't have access to the
original picture file -- or whether it will display some sort of error
message.

~~~~~~~~~

Instead of using an Image control, you can use a one-cell borderless table,
a text box, a bookmark, or several other items that are native to Word to
indicate where the picture should be inserted. A one-cell table has the
advantage that, with a little setup, it can automatically size whatever
picture you choose to insert.

In the template for your report document, insert the table (because you're
putting in a logo, I expect it will be the first table in the document,
which VBA addresses as ActiveDocument.Tables(1); if not, choose the correct
index number). With the table selected, click Table > AutoFit > Fixed Column
Width. In Table > Properties > Rows, set the minimum height you want. In the
cell, press Ctrl+Alt+U to turn off the border lines (or you can do this in
the Format > Borders dialog).

Then the macro code will look like this:

Sub InsertLogo()
Dim PicName As String
Dim oRg As Range

PicName = "C:\somefolder\somepicture.jpg" ' set as needed

Set oRg = ActiveDocument.Tables(1).Cell(1, 1).Range

' remove any existing picture in the table
While oRg.InlineShapes.Count
oRg.InlineShapes(1).Delete
Wend

ActiveDocument.InlineShapes.AddPicture _
FileName:=PicName, LinkToFile:=False, _
SaveWithDocument:=True, Range:=oRg
End Sub

There's no need to force an update here. Also, because of the LinkToFile and
SaveWithDocument settings, you're guaranteed that the image will travel with
the document file.
 
G

Greg Maxey

Hi Jay,

Interesting post. It got me thinking about a project that I was playing
with back in the winter that I gave up in frustration. I was trying to
programatically add an image to a picture content control and then "size"
the the image displayed in the document. I can get the image into the
control, but all attempts to then size it programatically seem to be
ignored:

I added one picture type CC to a document titled "LogoImageCC"

Sub GetMyPicture()
Dim SelectedFile As String
With Application.FileDialog(msoFileDialogFilePicker)
If .Show Then
SelectedFile = .SelectedItems(1)
Else
SelectedFile = ""
End If
End With
If SelectedFile = "" Then
MsgBox "You did not select a file"
Exit Sub
Else
InsertImageInContentControl SelectedFile
End If
End Sub

Sub InsertImageInContentControl(ByRef pName As String)
Dim oCC As Word.ContentControl
Dim oRng As Word.Range
Dim oILS As InlineShape
Dim y As Single
Set oCC = ActiveDocument.SelectContentControlsByTitle("LogoImageCC").Item(1)
Set oRng = oCC.Range
oRng.Delete
Application.ScreenUpdating = False
Set oILS = ActiveDocument.InlineShapes.AddPicture(FileName:=pName,
LinkToFile:=False, SaveWithDocument:=True, _
Range:=oRng)
'These lines run without error but have no visible effect on the image
displayed in the document.
With oILS
y = CSng(.Height) / CSng(.Width)
.Width = InchesToPoints(3) 'Sets width to 3 inches
.Height = y * .Width
End With
Application.ScreenUpdating = True
End Sub

Any ideas?

Thanks.
 
G

Greg Maxey

Jay,

While the .width and .height attributes seem to be ignored, the scalewidth
and scaleheight do work:

Sub InsertImageInContentControl(ByRef pName As String)
Dim oCC As Word.ContentControl
Dim oRng As Word.Range
Dim oILS As InlineShape
Dim y As Single
Set oCC = ActiveDocument.SelectContentControlsByTitle("LogoImageCC").Item(1)
Set oRng = oCC.Range
oRng.Delete
Set oILS = ActiveDocument.InlineShapes.AddPicture(FileName:=pName,
LinkToFile:=False, SaveWithDocument:=True, _
Range:=oRng)
With oILS
.LockAspectRatio = msoTrue
MsgBox .Width 'mine reads 468
'This is ignored
.Width = 150
MsgBox .Width 'still reads 468
'This effects the shape and changes the width
.ScaleWidth = 5
MsgBox .Width 'reads 102.4
End With
End Sub
 
J

Jay Freedman

Hi Greg,

I'm glad something works. I keep getting the feeling that the MS guys working on
the content control stuff in VBA only got about 2/3 of the way through the job
before it was ripped out of their hands and shipped. :( Let's hope for Office 14
they're allowed to finish!

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroup so all
may benefit.
 
G

Greg Maxey

Jay,

I agree!

I can select the oILS in the code and then use the Ribbon Contextual Tab
"Picture Tools>Format" Size dialogBox launcher fields to size the image.

I thought if I might somehow access that dialog in the code then I could use
its methods to size/scale the image. No joy so far. I can't find the name
or index of that particular dialog :-(

Thanks.
 
J

Jay Freedman

[snip]
After showing you the answer to your specific question, I'll point to a
better alternative.
[snip]

Instead of using an Image control, you can use a one-cell borderless table,
a text box, a bookmark, or several other items that are native to Word to
indicate where the picture should be inserted. A one-cell table has the
advantage that, with a little setup, it can automatically size whatever
picture you choose to insert.

In fact, I overlooked an even easier solution than the macro I showed before.

First, create a separate AutoText entry containing each logo you could use, plus
one that contains just a space character (for use when there is no appropriate
logo). Store these AutoText entries in the same template you use for the
reports. (http://www.word.mvps.org/FAQs/Customization/AutoText.htm)

Now, still in the template, go to File > Properties > Custom. Add a custom
property named Logo, of String type, and in the Value box enter the name of the
AutoText entry that consists of a space.

In the one-cell table or whatever place you've reserved in the template body,
insert the following nested field, using Ctrl+F9 to put in the field marker
braces:

{ AutoText { DocProperty Logo } }

Press F9 to update the field -- you won't see anything unless you turn on
nonprinting characters and show the small dot that represents the space.

Finally, add this macro (though I suggest replacing the InputBox with something
that ensures the entered string is the name of an existing AutoText entry -- for
example, a userform with a list box):

Sub ChangeLogo()
Dim logoName As String
logoName = InputBox("Enter company name")
If Len(logoName) Then
With ActiveDocument
.CustomDocumentProperties("Logo").Value _
= logoName
.Fields.Update
End With
End If
End Sub

When you run the macro and choose the name of one of the AutoText entries, that
name will be placed into the Logo property; the {DocProperty Logo} field will
evaluate to that string; and the AutoText field will display the content of the
corresponding AutoText entry. This can be changed as often as you like. It also
has the advantage that all the logos are stored in the single template file,
instead of being external graphics files.
 
G

Greg Maxey

Jay,

Still tinkering with this. I haven't been able to figure out how to insert
and size an image in a Picture type content control or how to
programattically format (size) a Picture type CC image, but I have
discovered how to insert and size an image in a RichText CC.

Sub GetMyPicture()
Dim SelectedFile As String
With Application.FileDialog(msoFileDialogFilePicker)
If .Show Then
SelectedFile = .SelectedItems(1)
Else
SelectedFile = ""
End If
End With
If SelectedFile = "" Then
MsgBox "You did not select a file"
Exit Sub
Else
InsertImageInContentControl SelectedFile
End If
End Sub

Sub InsertImageInContentControl(ByRef pName As String)
Dim oCC As Word.ContentControl
Dim oRng As Word.Range
Dim oILS As InlineShape
Dim y As Single
Set oCC = ActiveDocument.SelectContentControlsByTitle("LogoImage").Item(1)
Set oRng = oCC.Range
Application.ScreenUpdating = False
While oRng.InlineShapes.Count
oRng.InlineShapes(1).Delete
Wend
'On Error GoTo Err_Handler
oCC.Range.Text = " "
Set oILS = ActiveDocument.InlineShapes.AddPicture(FileName:=pName,
LinkToFile:=False, SaveWithDocument:=True, _
Range:=oRng)
'Size image
With oILS
y = CSng(.Height) / CSng(.Width)
.Width = InchesToPoints(3) 'Sets width to 3 inches
.Height = y * .Width
End With
oCC.Range.Characters.Last.Delete
Application.ScreenUpdating = True
'Exit Sub
'Err_Handler:
'oCC.Range.Text = " "
'Resume
End Sub

For some reason the procedures throws an error on the Set oILS line if the
content control is completely empty (i.e., showing placeholder text). To
avoid the error I can set the range.text to " " then clip the character at
the end.
 
J

Jay Freedman

Thanks. That's better than nothing.

The point of using the Picture control in a template, I think, is that it
doesn't accept anything except a picture. A Rich Text control would allow a user
to "decorate" the document with almost anything. If that matters for a
particular application, then it doesn't leave you with any alternatives.
 
G

Greg Maxey

Jay,

Yeah, I am really puzzled by the behaviour.

Starting with a new blank document I added a Picture CC (titled LogoImageCC)
and inserted a picture. Below that I inserted the same picture directly in
the document. Then ran this code:

Sub Test()
Dim oILS1 As InlineShape
Dim oILS2 As InlineShape
Set oILS1 =
ActiveDocument.SelectContentControlsByTitle("LogoImageCC").Item(1).Range.InlineShapes(1)
With oILS1
MsgBox .Width
.Width = 200 'Has no effect.
MsgBox .Width 'Reports same width as before attempted change
.ScaleWidth = 50
MsgBox .Width 'Reports revised width and image is in fact scaled.
End With
Set oILS2 = ActiveDocument.InlineShapes(2)
With oILS2
MsgBox .Width
.Width = 200 'physically changes width of image
MsgBox .Width 'Reports width changed to 200
End With
End Sub

Can't imagine why the inlineshape in the Picture CC is immune to the .width
change.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top