Word VBA, Get Picture Horizontal Position
In this article I will explain how you can get a pictures position using VBA for Word.
Step 1, Getting reference to the Image
As explained in the article below, pictures can either be inline or floating:
The first thing to do is to get a reference to the image.
In this example the reference of the first image will be stored in the object objPicture:
Note: The previous code will give reference to the first floating shape in the document. In order to get reference to the first inline shape we would have to use something like this:
For more information about floating and inline shapes, and the Shape and InlineShape collections please see the article below:
Using the code below you can get the position of the image:
For example for the document below:
The code below will return the second images position:
Probable Errors #1:
You can download the word document and try this yourself:
Step 1: Run the code and you will get the result in the previous section.
Step 2: Manually insert a caption for the first figure:
Step 3: As you can see this has cause the second image to move right. But if you run the code again you will get the same result:
It can be seen that the method explained in the previous section for getting the position of floating pictures isn’t reliable. If you right-click a picture in the word document and click on the size and position button, on the position tab you can see the position is displayed relative to the column:
This can be overcome by changing the position property from column to page. This can be done using the code below:
The benefits of making this change is twofold:
- The position function will always display the correct value
- The image will not move.
The complete code can be seen below:
Probable Error #2:
By changing the relative position from column to page, some of the floating pictures might get displaced. For example in the document below:
If you run the code below, the third image will get displaced:
This can be prevented by saving the relative position of the image before making the changes, and adjusting the images position after the changes.
The code below stores the 3rd pictures original position relative to the column (before the changes) and adjusts the position of the image after the changes:
The line below gets the position of the picture relative to the column before making the changes:
The line below sets the position of the image back to its original position:
Pagesetup.leftmargin is the distance of the column with the page.
You can download all the files and code related to this article from the link below:
- Word VBA, Adding Caption to Images
- Word VBA, Loop Through Images
- Word VBA, Removing Picture Captions
- Word VBA, Re-Adjust Caption