Send file, with images which are stored internally, to external recipients - vba

I send a file with images to clients. When the client opens the file all the images are gone or there is an error message. This document is updated weekly with new inventory data.
All images reference column E and images are saved to a folder within the company server.
The code I have been using is:
Sub IMAGEINSERT()
Dim pictureNameColumn As String 'column where picture name is found
Dim picturePasteColumn As String 'column where picture is to be pasted
Dim pictureName As String 'picture name
Dim lastPictureRow As Long 'last row in use where picture names are
Dim pictureRow As Long 'current picture row to be processed
Dim pathForPicture As String 'path of pictures
pictureNameColumn = "E"
picturePasteColumn = "A"
pictureRow = 2 'starts from this row
'error handler
On Error GoTo Err_Handler
'find row of the last cell in use in the column where picture names are
lastPictureRow = Cells(Rows.Count, pictureNameColumn).End(xlUp).Row
'stop screen updates while macro is running
Application.ScreenUpdating = False
pathForPicture = "M:\Sales\Accessories\Hope G\_OFF PRICE\_ATS REPORTS\ATS LIST\images\"
'loop till last row
Do While (pictureRow <= lastPictureRow)
pictureName = Cells(pictureRow, "E") 'This is the picture name
'if picture name is not blank then
If (pictureName <> vbNullString) Then
'check if pic is present
If (Dir(pathForPicture & pictureName & ".jpg") <> vbNullString) Then
'This is where picture will be inserted
Cells(pictureRow, picturePasteColumn).Select
'Path to where pictures are stored
ActiveSheet.Pictures.Insert(pathForPicture & pictureName & ".jpg").Select
With Selection
.Left = Cells(pictureRow, picturePasteColumn).Left
.Top = Cells(pictureRow, picturePasteColumn).Top
.ShapeRange.LockAspectRatio = msoFalse
.ShapeRange.Height = 80#
.ShapeRange.Width = 60#
.ShapeRange.Rotation = 0#
End With
Else
'picture name was there, but no such picture
Cells(pictureRow, picturePasteColumn) = ""
End If
Else
'picture name cell was blank
End If
'increment row count
pictureRow = pictureRow + 1
Loop
Exit_Sub:
Range("A10").Select
Application.ScreenUpdating = True
Exit Sub
Err_Handler:
MsgBox "Error encountered. " & Err.Description, vbCritical, "Error"
GoTo Exit_Sub
End Sub

I'm assuming that the clients you're sending the file to are external clients.
The Pictures.Insert method only creates a link to the picture, so external clients which don't have access to your company server won't be able to see the pictures.
You need to instead use the Shapes.AddPicture method, which can embed the picture in the file.
Activesheet.Shapes.AddPicture Filename:=pathForPicture & pictureName & ".jpg", _
LinkToFile:=msoFalse, SaveWithDocument:=msoTrue, _
Left:=Selection.Left, Top:=Selection.Top, Width:=-1, Height:=-1
Note that the Width and Height parameters are mandatory, but you can set them to -1, which then maintains the height and width of the original image!

Related

Picture doesn't get inserted into the Excel file (but only as a reference)

After image inserted in Excel file error
The linked image cannot be displayed. The file may have been moved, renamed, or deleted. Verify that the link points to the correct file and location
is coming when I have share to other and as per mentioned code use in macro. Please I request to you any one help. (I'm using Windows 10 and Excel 10)
Sub Macro1()
'
' Macro1 Macro
'
' Keyboard Shortcut: Ctrl+p
'
Dim pictureNameColumn As String 'column where picture name is found
Dim picturePasteColumn As String 'column where picture is to be pasted
Dim pictureName As String 'picture name
Dim lastPictureRow As Long 'last row in use where picture names are
Dim pictureRow As Long 'current picture row to be processed
Dim pathForPicture As String 'path of pictures
pictureNameColumn = "A"
picturePasteColumn = "E"
pictureRow = 5 'starts from this row
'error handler
On Error GoTo Err_Handler
'find row of the last cell in use in the column where picture names are
lastPictureRow = Cells(Rows.Count, pictureNameColumn).End(xlUp).Row
'stop screen updates while macro is running
Application.ScreenUpdating = False
pathForPicture = "C:\Users\Nimit\Desktop\Dimensional\Insert Image\"
'loop till last row
Do While (pictureRow <= lastPictureRow)
pictureName = Cells(pictureRow, "A") 'This is the picture name
'if picture name is not blank then
If (pictureName <> vbNullString) Then
'check if pic is present
'Start If block with .JPG
If (Dir(pathForPicture & pictureName & ".jpg") <> vbNullString) Then
Cells(pictureRow, picturePasteColumn).Select 'This is where picture will be inserted
ActiveSheet.Pictures.Insert(pathForPicture & pictureName & ".jpg").Select 'Path to where pictures are stored
With Selection
.Left = Cells(pictureRow, picturePasteColumn).Left
.Top = Cells(pictureRow, picturePasteColumn).Top
.ShapeRange.LockAspectRatio = msoFalse
.ShapeRange.Height = 45#
.ShapeRange.Width = 55#
.ShapeRange.Rotation = 0#
End With
'End If block with .JPG
'Start ElseIf block with .PNG
ElseIf (Dir(pathForPicture & pictureName & ".png") <> vbNullString) Then
Cells(pictureRow, picturePasteColumn).Select 'This is where picture will be inserted
ActiveSheet.Pictures.Insert(pathForPicture & pictureName & ".png").Select 'Path to where pictures are stored
With Selection
.Left = Cells(pictureRow, picturePasteColumn).Left
.Top = Cells(pictureRow, picturePasteColumn).Top
.ShapeRange.LockAspectRatio = msoFalse
.ShapeRange.Height = 45#
.ShapeRange.Width = 50#
.ShapeRange.Rotation = 0#
End With
'End ElseIf block with .PNG
'Start ElseIf block with .BMP
ElseIf (Dir(pathForPicture & pictureName & ".bmp") <> vbNullString) Then
Cells(pictureRow, picturePasteColumn).Select 'This is where picture will be inserted
ActiveSheet.Pictures.Insert(pathForPicture & pictureName & ".bmp").Select 'Path to where pictures are stored
With Selection
.Left = Cells(pictureRow, picturePasteColumn).Left
.Top = Cells(pictureRow, picturePasteColumn).Top
.ShapeRange.LockAspectRatio = msoFalse
.ShapeRange.Height = 45#
.ShapeRange.Width = 50#
.ShapeRange.Rotation = 0#
End With
'End ElseIf block with .BMP
Else
'picture name was there, but no such picture
Cells(pictureRow, picturePasteColumn) = "No Picture Found"
End If
Else
'picture name cell was blank
End If
'increment row count
pictureRow = pictureRow + 1
Loop
Exit_Sub:
Range("A10").Select
Application.ScreenUpdating = True
Exit Sub
Err_Handler:
MsgBox "Error encountered. " & Err.Description, vbCritical, "Error"
GoTo Exit_Sub
End Sub
ActiveSheet.Pictures.Insert always inserts a picture as a reference to a file. If the picture file is missing on other computers (when you share the Excel file) it can't be displayed.
To insert a picture permanently into an Excel file try the following:
ActiveSheet.Shapes.AddPicture Filename:="C:\Temp\barcode.png", LinkToFile:=msoFalse, SaveWithDocument:=msoCTrue, Left:=Selection.Left, Top:=Selection.Top, Width:=-1, Height:=-1
See here for the reference to the Shapes.AddPicture method.

Excel VBA - insert bulk images in sheet

I am using below vba code to get images in excel sheet but this code add images in sheet as link, so when i am sending sheet to another pc that person get image location not found error.
How can i add attach images in sheet instead of link of image???
Sub AddOlEObject()
Dim mainWorkBook As Workbook
Set mainWorkBook = ActiveWorkbook
Sheets("Object").Activate
Folderpath = "C:\phoenix"
Set fso = CreateObject("Scripting.FileSystemObject")
NoOfFiles = fso.GetFolder(Folderpath).Files.Count
Set listfiles = fso.GetFolder(Folderpath).Files
For Each fls In listfiles
strCompFilePath = Folderpath & "\" & Trim(fls.name)
If strCompFilePath <> "" Then
If (InStr(1, strCompFilePath, ".jpg", vbTextCompare) > 1) Then
counter = counter + 1
Sheets("Object").Range("A" & counter).Value = fls.name
Sheets("Object").Range("B" & counter).ColumnWidth = 50
Sheets("Object").Range("B" & counter).RowHeight = 150
Sheets("Object").Range("B" & counter).Activate
Call insert(strCompFilePath, counter)
Sheets("Object").Activate
End If
End If
Next
End Sub
Function insert(PicPath, counter)
'MsgBox PicPath
With ActiveSheet.Pictures.insert(PicPath)
With .ShapeRange
.LockAspectRatio = msoTrue
.Width = 100
.Height = 150
End With
.Left = ActiveSheet.Range("B" & counter).Left
.Top = ActiveSheet.Range("B" & counter).Top
.Placement = 1
.PrintObject = True
End With
End Function
Is the Image a single image that you have saved in a personal directory that you use frequently? Also is the image saved as .JPEG?
why don't you use a simple VBA code below?
Sub CALLPICTURE()
Worksheets("SHEET1").Shapes.AddPicture Filename:="I:\Control\DECOMP\ Images\Zebra.jpg", linktofile:=msoFalse, _
savewithdocument:=msoCTrue, Left:=0, Top:=0, Width:=632, Height:=136
End Sub
You could add as many images as you want to.

click shape or button (preview/close) that displays an image

I am new to VBA and seeking help on a work project. I have done some research and got started but am now over my head.
My objectives are:
Create a click shape or button (preview/close) that displays an image from another location on computer.
The image displayed will be dependent on the data input (col A: patient name; same name of jpeg image) for each name that is entered in the same row.
Also I would like a new button/shape to be automatically created in the corresponding cell when a new name is added
Thanks Rick
Sub Macro1()
Dim Path As String
Set myDocument = Worksheets(1)
Path = "F:\CAD_CAM division\Unsorted Models\"
myDocument.Pictures.Insert (Path & ActiveCell.Value & ".jpg")
With ActiveSheet.Shapes("Rounded Rectangle 1").TextFrame2.TextRange.Characters
If .Text = "Close" Then
.Text = "Preview"
ActiveSheet.Pictures.Delete
Else
.Text = "Close"
With ActiveSheet.Shapes("Rounded Rectangle 1")
End With
End If
End With
End Sub
While your original code was actually working, I made a few slight adjustments to ensure that all (multiple) pictures are included / shown on the sheet and to align these picture below each other. Have a look at the comments in the code and let me know what you think:
Option Explicit
Sub Macro1()
Dim lngRow As Long
Dim strPath As String
Dim picItem As Picture
Dim shtPatient As Worksheet
'If there are multiple pictures then they should be shown
' underneath each other. dblLeft and dblTop will be used
' to place the next picture underneath the last one.
Dim dblTop As Double
Dim dblLeft As Double
Set shtPatient = ThisWorkbook.Worksheets(1)
strPath = "F:\CAD_CAM division\Unsorted Models\"
With shtPatient.Shapes("Rounded Rectangle 1").TextFrame2.TextRange.Characters
If .Text = "Close" Then
.Text = "Preview"
ActiveSheet.Pictures.Delete
Else
.Text = "Close"
For lngRow = 2 To shtPatient.Cells(shtPatient.Rows.Count, "A").End(xlUp).Row
'First check if the file actually exists / can be found and inserted
If Dir(strPath & shtPatient.Cells(lngRow, 1).Value2 & ".jpg") <> "" Then
Set picItem = shtPatient.Pictures.Insert(strPath & shtPatient.Cells(lngRow, 1).Value2 & ".jpg")
'Name the picture so it can be found afterwards again using VBA
picItem.Name = shtPatient.Cells(lngRow, 1).Value2 & ".jpg"
If lngRow = 2 Then
picItem.Top = shtPatient.Range("F2").Top
picItem.Left = shtPatient.Range("F2").Left
dblTop = picItem.Top + picItem.Height + 10
dblLeft = picItem.Left
Else
picItem.Top = dblTop
picItem.Left = dblLeft
dblTop = picItem.Top + picItem.Height + 10
End If
End If
Next lngRow
End If
End With
End Sub

VBA how to copy images / inline shapes from Word to powerpoint

I am trying to write a macro to find and copy all the graphs/images inline in a word document and paste them into individual slides in a new powerpoint. However when I run into multiple runtime errors. Here's the entire code.
Sub wordtoppt()
'This macro copies all pictures out of a word document of your choice and into a new powerpoint presentation.
'Two reference libraries need to be open - Word and Powerpoint. Go Tools > References, and tick the relevant box.
Dim wdApp As Word.Application 'Set up word and powerpoint objects
Dim wdDoc As Word.Document
Dim pptApp As PowerPoint.Application
Dim pptShw As PowerPoint.Presentation
Dim pptChart As PowerPoint.Shape
Dim pptSld As PowerPoint.Slide
On Error GoTo 0
Dim wcount As Integer 'Number of open word documents
Dim doclist() As String 'Collects the names of open word documents
Dim desc As String 'inputbox text
Dim chosendoc As Integer 'stores the index number of your selected word document
Dim ccount As Integer 'number of shapes in the word document
Dim wellpasted As Integer 'Counts the number of shapes that have successfully been pasted into powerpoint.
Application.ScreenUpdating = False
'Establishes link with word.
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
On Error GoTo 0
If wdApp Is Nothing Then 'Error message if Word is not open
MsgBox "Error: Word is not open." & Chr(10) & Chr(10) & "Is word actually open? This is a bug."
Exit Sub
End If
'Counts the number of word documents open
wcount = CInt(wdApp.Documents.Count)
ReDim doclist(wcount) 'resizes string array of word documents
If wcount = 0 Then 'Error message if Word is open, but there are no documents open
MsgBox "There are no word documents open!" & Chr(10) & "Open a word document and try again"
Exit Sub
End If
'text for input box
desc = "Which document would you like to extract the graphs from?" & Chr(10) & Chr(10) & "Type the number in the box (one number only)." & Chr(10) & Chr(10)
'input boxes for selection of word document
If wcount = 1 Then 'if only one document open
myinput = MsgBox("Do you want to paste graphs from " & wdApp.Documents(1).Name & "?", vbYesNo, "From Release Note to Powerpoint")
If myinput = vbYes Then
chosendoc = 1
Else
Exit Sub
End If
Else
For i = 1 To wcount 'multiple documents open
doclist(i) = wdApp.Documents(i).Name
desc = desc & i & ": " & doclist(i) & Chr(10)
Next
myinput = InputBox(desc, "From Release Note to Powerpoint")
If IsNumeric(myinput) And myinput <= wcount Then 'Error handling - if cancel is clicked, or anything other than a number is typed into the input box.
chosendoc = CInt(myinput)
Else
If myinput = "" Then 'clicking cancel, or leaving input box blank
MsgBox "You didn't enter anything!"
Exit Sub
Else 'if you type a short novel
MsgBox "You didn't enter a valid number!" & Chr(10) & "(Your response was " & myinput & ")"
Exit Sub
End If
End If
End If
'Error handling, for chart-free word documents.
If wdApp.Documents(chosendoc).InlineShapes.Count = 0 Then
MsgBox "There are no charts in this Word Document!"
Exit Sub
End If
'Opens a new powerpoint presentation
Set pptApp = CreateObject("PowerPoint.Application")
Set pptShw = pptApp.Presentations.Add
'PowerPoint.Application
'Sets up slide dimensions
Dim sldwidth As Integer
Dim sldheight As Integer
sldwidth = pptShw.PageSetup.SlideWidth
sldheight = pptShw.PageSetup.SlideHeight
wellpasted = 0
Dim shapecount As Integer 'Number of shapes in the word document
shapecount = wdApp.Documents(chosendoc).InlineShapes.Count
For j = 1 To shapecount 'Adds in the correct number of slides into the powerpoint presentation
Set pptSld = pptShw.Slides.Add(pptShw.Slides.Count + 1, ppLayoutBlank)
Next
For j = 1 To shapecount 'loops through all shapes in the document
On Error GoTo Skiptheloop 'sometimes some objects don't paste. This is a way to skip over them.
'Application.Wait Now + (1 / 86400)
wdApp.Documents(chosendoc).InlineShapes(j).Range.Copy 'copies chart
Set pptSld = pptShw.Slides(j)
pptSld.Shapes.Paste 'pastes chart
'Application.CutCopyMode = False
With pptSld.Shapes(1) 'resizes and aligns shapes
.LockAspectRatio = msoTrue 'Currently sets charts to the height of the slide. Alternatively can scale to 100%
.Height = sldheight
.Left = (sldwidth / 2) - (.Width / 2)
.Top = (sldheight / 2) - (.Height / 2)
End With
wellpasted = wellpasted + 1 'if the chart was pasted successfully, increment by 1.
Skiptheloop:
Next
On Error GoTo 0
If (shapecount - wellpasted) <> 0 Then 'produces a message box if some shapes did not paste successfully.
MsgBox CStr(shapecount - wellpasted) & " (of " & CStr(shapecount) & ") shapes were not pasted. Best that you check all the graphs are in."
End If
Application.ScreenUpdating = True
pptApp.Activate 'brings powerpoint to the front of the screen
Exit Sub
End Sub
On the line pptSld.shapes.paste I get the error clipboard empty or cannot paste.
Any ideas?
I am using Simple solution for my job devided in two pars
1) Extract all images from word file
This can be done in two ways.
a. save as html which will create the folder filenam_files which will hold all the images in .png formate. There may be duplicate images in diff formate but .png will be unique.
b. change filename of word from file.docx to file.docx.zip
You can get the images at file.docx\word\media
There will be no duplicate images in this method.
2) Import all images in powerpoint.
1)
As you have already opened the document manually you can do one more step manually or record macro which will look like this.
Sub exportimages()
ChangeFileOpenDirectory "D:\temp\"
ActiveDocument.SaveAs2 FileName:="data.html", FileFormat:=wdFormatHTML, _
LockComments:=False, passWord:="", AddToRecentFiles:=True, WritePassword _
:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts:=False, _
SaveNativePictureFormat:=False, SaveFormsData:=False, SaveAsAOCELetter:= _
False, CompatibilityMode:=0
End Sub
2)
Close the word document.
Open Power point and paste this
Sub ImportABunch()
Dim strTemp As String
Dim strPath As String
Dim strFileSpec As String
Dim oSld As Slide
Dim oPic As Shape
strPath = "D:\temp\data_files\"
strFileSpec = "*.png" 'if you are using mehtod **a.** to extract the images.
'strFileSpec = "*.*" 'if you are using mehtod **b.** to extract the images.
strTemp = Dir(strPath & strFileSpec)
Do While strTemp <> ""
Set oSld = ActivePresentation.Slides.Add(ActivePresentation.Slides.Count + 1, ppLayoutBlank)
Set oPic = oSld.Shapes.AddPicture(FileName:=strPath & strTemp, _
LinkToFile:=msoFalse, _
SaveWithDocument:=msoTrue, _
Left:=0, _
Top:=0, _
Width:=-1, _
Height:=-1)
strTemp = Dir
Loop
End Sub
You can write vbscript to combine this two steps together. I have no idea how to do that. You can google it.

Macro to search for pictures in subfolders [duplicate]

This question already has answers here:
Cycle through sub-folders and files in a user-specified root directory [duplicate]
(3 answers)
Closed 7 years ago.
I will realy appreciate your help on this issue. I'm quite new with macro.
The macro that I'm using is inserting a picture in Excel column A cells by taking the file name reference from the column B cells.
I have the following macro that works just fine if I know the subfolder were to search for the picture that I need but I don't know how to do it to search in all subfolders of Z:\mfs\PictureLibrary.
Here is the macro :
Sub Picture()
Dim picname As String
Dim pasteAt As Integer
Dim lThisRow As Long
lThisRow = 2
Do While (Cells(lThisRow, 2) <> "")
pasteAt = lThisRow
Cells(pasteAt, 1).Select 'This is where picture will be inserted
picname = Cells(lThisRow, 2) 'This is the picture name
present = Dir("Z:\mfs\PictureLibrary\Codello A14 Transfer\" & picname & ".jpg")
If present <> "" Then
ActiveSheet.Pictures.Insert("Z:\mfs\PictureLibrary\Codello A14 Transfer\" & picname & ".jpg").Select 'Path to where pictures are stored
'''''''''''''''''''''''''''''''''''''''''''''''''''''''
' This resizes the picture
'''''''''''''''''''''''''''''''''''''''''''''''''''''''
With Selection
'.Left = Range("A2").Left
'.Top = Range("A2").Top
.Left = Cells(pasteAt, 1).Left
.Top = Cells(pasteAt, 1).Top
.ShapeRange.LockAspectRatio = msoFalse
.ShapeRange.Height = 55#
.ShapeRange.Width = 40#
.ShapeRange.Rotation = 0#
End With
Else
Cells(pasteAt, 1) = ""
End If
lThisRow = lThisRow + 1
Loop
Range("A10").Select
Application.ScreenUpdating = True
Exit Sub
ErrNoPhoto:
MsgBox "Unable to Find Photo" 'Shows message box if picture not found
Exit Sub
Range("B20").Select
End Sub
Please, check the example below, it iterates through subfolders and search for your file, you just have to fit it in your code:
Dim FileSystem As Object
Const mainFolder As String = "Z:\mfs\PictureLibrary\Codello A14 Transfer\"
Sub YourProblem()
Dim filePath As String
filePath = Find("pictureName.jpg")
MsgBox filePath
End Sub
Function Find(picName As String) As String
Set FileSystem = CreateObject("Scripting.FileSystemObject")
Find = FindPicture(FileSystem.GetFolder(mainFolder), picName)
End Function
Function FindPicture(innerFolder, picName As String) As String
Dim pictureFound As String
pictureFound = Dir(innerFolder & "\" & picName)
If Len(Trim(pictureFound)) > 0 Then
FindPicture = innerFolder & "\" & pictureFound
Exit Function
Else
Dim subFolder
For Each subFolder In innerFolder.SubFolders
pictureFound = FindPicture(subFolder, picName)
If Len(Trim(pictureFound)) > 0 Then
FindPicture = pictureFound
Exit Function
End If
Next
End If
End Function