Insert Image to Word, Resize Image, Insert Borders using VBA Excel
The program inserts an image to a word file and resizes the images and inserts a border.
ExplanationThis VBA program is developed to extract an image and insert it to word file resize the image according the settings in the worksheet and surround the image with a border. The image can be re-sized using this code but the image will not change in terms of size in kilobytes. To compress an image using VBA is not possible this has to be done manually.
In order to make the program work the reference “Microsoft Word XX.X Object Library” needs to be enabled.
Example file of the VBA code is available for downloading at the bottom of this web page, enjoy! Or just copy and paste the code directly from this page.
CodePublic Sub Insert_Image_to_Word_Resize_Image_Insert_Borders_using_VBA_Excel()
Dim Insert_Image_to_Word_Resize_Image_Insert_Borders_using_VBA_Excel_APP As Word.Application
Dim Insert_Image_to_Word_Resize_Image_Insert_Borders_using_VBA_Excel_DOC As Word.Document
Set Insert_Image_to_Word_Resize_Image_Insert_Borders_using_VBA_Excel_APP = CreateObject("Word.Application")
Dim PlaceOfWordFile As String
Dim NameOfWordFile As String
PlaceOfWordFile = Range("B4").Value
NameOfWordFile = Range("B5").Value
PlaceOfImageFile = Range("B6").Value
NameOfImageFile = Range("B7").Value
NamePlaceImage = PlaceOfImageFile + "\" + NameOfImageFile
NamePlace = PlaceOfWordFile + "\" + NameOfWordFile
Insert_Image_to_Word_Resize_Image_Insert_Borders_using_VBA_Excel_APP.Visible = True
Set Insert_Image_to_Word_Resize_Image_Insert_Borders_using_VBA_Excel_DOC = Insert_Image_to_Word_Resize_Image_Insert_Borders_using_VBA_Excel_APP.Documents.Open(NamePlace, ReadOnly:=False)
Set WORD_Image = Insert_Image_to_Word_Resize_Image_Insert_Borders_using_VBA_Excel_APP.Selection.InlineShapes.AddPicture(NamePlaceImage, False, True)
HeightOfImage = Range("D5").Value
H = .Height
B = .Width
Ratio = H / B
.Height = HeightOfImage
.Width = HeightOfImage / Ratio
WORD_Image.Borders.OutsideLineStyle = wdLineStyleSingle
Set Insert_Image_to_Word_Resize_Image_Insert_Borders_using_VBA_Excel_DOC = Nothing
Set Insert_Image_to_Word_Resize_Image_Insert_Borders_using_VBA_Excel_APP = Nothing
Download excel file! Insert_Image_to_Word_Resize_Image_Insert_Borders_using_VBA_Excel.xls
CommentsYou should really put "Option Explicit" at the top of your module. Assuming of course the variables not dimensionalized in this subroutine are not public variables declared outside it, which you just failed to mention. You should adopt some better practices when producing code for others. Aside from that, thanks for the code.
Comment made by: Kevin , 2010-10-22 15:35:05
How i can use this code to a word document selecting the photos and use this code to assing a border to it?
Comment made by: Elvis , 2011-08-11 02:35:21