问题
I'm new to VBA and still struggling a lot.
I have a list object on a useform that is populated with the file-names of the contents of the relative ".\logos\" directory. I want to insert the picture at a bookmark named bmLogo
, but the code I've written (see below) doesn't do the trick.
If ListLogo <> Null Then
ActiveDocument.Bookmarks("bmLogo").Range _
.InlineShapes.AddPicture FileName:=ThisDocument.Path & "\logos\" & ListLogo
End If
Any tips? Also, if I could set a height and have the image scale to it without changing the aspect ratio that would be very useful!
Thanks,
Louis
EDIT 1: Right, so, bmLogo is the correct name of the bookmark, so that's not the problem. I just used a msgbox to display '"path: " & ThisDocument.Path & "\logos\" & ListLogo' and it looks like the correct path. I'm using ThisDocument.Path as I want it to be relative so the document is more portable. I think I'll try with an absolute path for the time being and seeing if that work, if nothing else it should hint at where the bug is not.
EDIT 2: It works with an absolute path outside the IF statement and when I get a msgbox to print both the absolute and relative path they are identical. After commenting out the IF statement the relative method works find. I'm glad that it's working now but can anyone tell what the issue is with the IF?
EDIT 3: It turns out that my method for checking if something has been selected in the list box doesn't work at all. Instead I shall be iterating through each item in the list and checking if that one is selected. It's a pretty crude method but it'll do until I can find a better one.
回答1:
For the record, this works for me in 2010, so I'm guessing there's either a problem with your filename (ListLogo
), your bookmark (bmLogo
), or else the filepath (ThisDocument.Path
).
1:
Does the filename match the format you expect? Is it just the filename, or a full path? Does it include the proper extension?
2:
Does the bookmark exist in your document?
3:
Does ThisDocument
refer to what you think it does? The simplification below works for me.
ActiveDocument.Bookmarks("TEST").Range.InlineShapes.AddPicture FileName:="P:\test.png"
I saved the .docx
file in my P:\
path, so the following should have worked:
ActiveDocument.Bookmarks("TEST").Range.InlineShapes.AddPicture FileName:=ThisDocument.Path & "\test.png"
However, the path returned was my AppData directory. When I watched the ThisDocument
object, I saw that it actually pointed to the Normal.dotm
template, where the code was created when I recorded a macro to test this out.
Can you please verify that each of these three items are correct and what you expect?
- ListLogo
- bmLogo
- ThisDocument
来源:https://stackoverflow.com/questions/16152041/inserting-a-picture-at-a-bookmark-or-how-to-tell-if-any-list-box-items-have-bee