Inserting and resizing pics

stltom554

New Member
Joined
Aug 1, 2015
Messages
27
I will apologize up front. I am not a VBA guy. I have modified some code in the past but even with what I am finding here I can't seem to put it all together.

What I have is a site survey where techs need to add pictures into one particular sheet. I need to accomplish the following:

  1. Import the picture to a specific cell (Ideally I would like to hide the button in the cell and click on the open cell which would keep it looking clean.
  2. Automatically size the photo to the same size as the cell
  3. Automatically add code/macro to the photo upon import which will allow the end user (customer) to click on the picture when reviewing the survey, and it pops up to it's original size in the middle of the screen, and another click to bring it back down.

Some of my problem may arise from me using the developer tools on my Mac. I am not sure.

Thank you in advance for your assistance[TABLE="width: 1173"]
<colgroup><col><col><col></colgroup><tbody>[TR]
[TD][/TD]
[TD][/TD]
[TD][/TD]
[/TR]
[TR]
[TD][/TD]
[TD][/TD]
[TD] [/TD]
[/TR]
[TR]
[TD]Perspective Photo of Outside MPOE (leading into)[/TD]
[TD] [/TD]
[TD] [/TD]
[/TR]
[TR]
[TD]MPOE Room Perspectives (take a few if possible)[/TD]
[TD] [/TD]
[TD] [/TD]
[/TR]
</tbody>[/TABLE]
 

Excel Facts

Lock one reference in a formula
Need 1 part of a formula to always point to the same range? use $ signs: $V$2:$Z$99 will always point to V2:Z99, even after copying
My intent was to allow the tech to select a cell then click on a button in the Quick Access toolbar to trigger the insert an image code. If the code to insert an image triggers whenever a cell is clicked I figured that would be an undesirable situation.
Can I rename the picture to match the cell address where it is inserted? This will be a simple way to know where it should be placed when it is full size and clicked on.
Can multiple pictures be enlarged at once? Or should a large one shrink if another one in a cell is clicked?
Can a full sized picture be larger than the screen?
Do you want to maintain the aspect ratio of the picture inserted into a cell (will likely have some whitespace in cell on site or bottom) or deform it to fit the full cell (no white space in cell).
 
Upvote 0
Copy the Private Sub to the code page of the worksheet where images will be inserted.
Copy the code to a new standard module
A right-click in a cell will trigger the insert image code
Aspect ratios will be retained for the small pictures
Image names will be change to match the address where they are inserted.

Code:
Option Explicit

Private Declare Function SetCurrentDirectoryA Lib "kernel32" _
    (ByVal lpPathName As String) As Long

Const bKeepPixAspectRatio As Boolean = True

'Add the Private Sub below to all worksheets where you want to insert pictures
'When a cell is right-clicked the code to insert a photo will be triggered
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
    InsertPictureIntoSelectedCell
End Sub
'End Add the Private Sub

'https://www.mrexcel.com/forum/excel-questions/1039443-inserting-resizing-pics.html

Sub InsertPictureIntoSelectedCell()
    'Assumes original picture size is larger than the cell size
    'Assumes original aspect ration should be retained
    
    Dim sCellAddr As String
    Dim sngCellHeight As Single
    Dim sngCellWidth As Single
    Dim sngPixHeight As Single
    Dim sngPixWidth As Single
    Dim sFilePathNameExt As String
    Dim sFilePath As String
    Dim sFileNameExt As String
    
    If Selection.Cells.Count > 1 Then
        MsgBox "Select the single cell where the picture will be inserted.", , "Select 1 Cell"
        GoTo End_Sub
    End If
    
    sngCellHeight = Selection.Height
    sngCellWidth = Selection.Width
    sCellAddr = Selection.Address(False, False)
    
    'Select File to Import
    
    Dim sFileName As String
    Dim sFileExt As String
    Dim vInput As Variant
    Dim vProcess() As String
    Dim lInputCount As Long
    Dim lFileIndex As Long
    Dim lFinalPathSepLoc As Long
    Dim s1Input As String
    Dim sServer As String
    Dim sIniPath As String
    Dim sFullPathFileName As String
    Dim lSuccess As Long
    Const bMultiSelect As Boolean = False
    Dim sngRatioToFit As Single
    
    sIniPath = CurDir
    
    'Set location that the directory search should start
    If ThisWorkbook.Path = vbNullString Then
        ChDir Environ("USERPROFILE") & "\Pictures\"
        ChDrive Environ("USERPROFILE") & "\Pictures\"
    Else
        If Left(ThisWorkbook.Path, 2) = "\\" Then
           lSuccess = SetCurrentDirectoryA(ThisWorkbook.Path)
            If lSuccess = 0 Then MsgBox "Unable to connect to " & vbLf & vbLf & _
                sServer: Exit Sub
        Else
            'Change ThisWorkbook.Path in next 2 statements to environ("USERPROFILE") & "\Pictures\" if
            '   The initial image directory should be the user's picture directory
            'ChDrive ThisWorkbook.Path
            'ChDir ThisWorkbook.Path
            ChDir Environ("USERPROFILE") & "\Pictures\"
            ChDrive Environ("USERPROFILE") & "\Pictures\"
            
        End If
    End If
    
    vInput = True
    'Open the standard Open dialog box at the specified location
    vInput = Application.GetOpenFilename("All Files (*.*), *.*", _
        , "Select a picture file to insert into the selected cell", "Only Mac Button Face", bMultiSelect)
        'If Cancel is selected vInput is always False
        'With MS True when one or more files are selected vInput is an array
        'With MS False when one file is selected vInput is a string
        
    On Error Resume Next  'Will cause an error if nothing selected
    If vInput <> False Then
        sFilePathNameExt = vInput
        On Error GoTo 0
            s1Input = sFilePathNameExt
            lFinalPathSepLoc = InStrRev(s1Input, Application.PathSeparator)
            sFilePath = CStr(Left(s1Input, lFinalPathSepLoc))
            sFileNameExt = CStr(Mid(s1Input, lFinalPathSepLoc + 1))
            sFileName = Left(sFileNameExt, InStr(sFileNameExt, ".") - 1)
            sFileExt = Mid(sFileNameExt, InStr(sFileNameExt, ".") + 1)
            
            '(Do stuff here with each filename in loop)

        'Next
    Else
        'User cancelled image selection
        GoTo End_Sub
    End If
    On Error GoTo 0
    
    
    ActiveSheet.Pictures.Insert(sFilePathNameExt).Select
    
    If bKeepPixAspectRatio Then
        
        If Selection.Height / sngCellHeight > Selection.Width / sngCellWidth Then
            sngRatioToFit = sngCellHeight / Selection.Height
        Else
            sngRatioToFit = sngCellWidth / Selection.Width
        End If
        Selection.ShapeRange.LockAspectRatio = msoTrue
        Selection.ShapeRange.ScaleHeight sngRatioToFit, msoFalse, msoScaleFromTopLeft

    Else
        Selection.ShapeRange.LockAspectRatio = msoFalse
        Selection.Height = sngCellHeight
        Selection.Width = sngCellWidth
    End If
    
    Selection.OnAction = "TogglePict"
    Selection.Name = sCellAddr
    
End_Sub:

End Sub


Sub TogglePict()
    'Assumes the original picture size is larger than the cell size
    
    Dim sName As String
    Dim sCellAddr As String
    
    Dim sngCellHeight As Single
    Dim sngCellWidth As Single
    Dim sngCellRatio As Single
    
    Dim sngPixHeight As Single
    Dim sngPixWidth As Single
    Dim sngPixRatio As Single
    
    Dim sngOrigPixHeight As Single
    Dim sngOrigPixWidth As Single
    Dim sngOrigPixRatio As Single
    
    Dim sngRatioToFit As Single
    
    sName = Application.Caller
    
    sngOrigPixHeight = ActiveSheet.Shapes(sName).Height
    sngOrigPixWidth = ActiveSheet.Shapes(sName).Width
    sngOrigPixRatio = sngOrigPixHeight / sngOrigPixWidth
    
    sngCellHeight = Range(sName).Height
    sngCellWidth = Range(sName).Width
    sngCellRatio = sngCellHeight / sngCellWidth
    
    If sngOrigPixHeight <= sngCellHeight And sngOrigPixWidth <= sngCellWidth Then
        'Picture is shrunk in the cell, so enlarge it and center it
        ActiveSheet.Shapes(sName).LockAspectRatio = msoFalse
        sngPixHeight = ActiveSheet.Shapes(sName).ScaleHeight(1, msoTrue)
        sngPixWidth = ActiveSheet.Shapes(sName).ScaleWidth(1, msoTrue)
        ActiveSheet.Shapes(sName).LockAspectRatio = msoTrue
        
        ActiveSheet.Shapes(sName).Left = (ActiveWindow.Width - ActiveSheet.Shapes(sName).Width) / 2
        ActiveSheet.Shapes(sName).Top = (ActiveWindow.Height - ActiveSheet.Shapes(sName).Height) / 2
        ActiveSheet.Shapes(sName).ZOrder msoBringToFront
    Else
        'Picture is out of the cell and needs to be put into it
        If bKeepPixAspectRatio Then
            
            If ActiveSheet.Shapes(sName).Height / sngCellHeight > ActiveSheet.Shapes(sName).Width / sngCellWidth Then
                sngRatioToFit = sngCellHeight / ActiveSheet.Shapes(sName).Height
            Else
                sngRatioToFit = sngCellWidth / ActiveSheet.Shapes(sName).Width
            End If
            ActiveSheet.Shapes(sName).LockAspectRatio = msoTrue
            ActiveSheet.Shapes(sName).ScaleHeight sngRatioToFit, msoFalse, msoScaleFromTopLeft
        Else
            ActiveSheet.Shapes(sName).ShapeRange.LockAspectRatio = msoFalse
            ActiveSheet.Shapes(sName).Height = sngCellHeight
            ActiveSheet.Shapes(sName).Width = sngCellWidth
        End If
        ActiveSheet.Shapes(sName).Left = Range(sName).Left
        ActiveSheet.Shapes(sName).Top = Range(sName).Top
        ActiveSheet.Shapes(sName).ZOrder msoSendToBack
        
    End If
    
    Application.ScreenUpdating = True
    
    
End Sub
 
Upvote 0
Can I rename the picture to match the cell address where it is inserted? This will be a simple way to know where it should be placed when it is full size and clicked on. Yes
Can multiple pictures be enlarged at once? Or should a large one shrink if another one in a cell is clicked? Shrink the original back down. The idea is to give the user the ability to quickly see the detail of the equipment, pathways, etc contained within the photo
Can a full sized picture be larger than the screen? No.
Do you want to maintain the aspect ratio of the picture inserted into a cell (will likely have some whitespace in cell on site or bottom) or deform it to fit the full cell (no white space in cell). Yes. Please.
 
Upvote 0
When I right click I am getting a compile error:

"The code in this project must be updated for use on 64-bit systems. Please review and update Declare statements and then mark them with the PtrSafe attribute"
 
Upvote 0
Ok. I fixed that problem on my own but now it is failing with a Run-tim error '76': Path not found. And when I debug it stops at the bolded portion of the code below:

Else
'Change ThisWorkbook.Path in next 2 statements to environ("USERPROFILE") & "\Pictures" if
' The initial image directory should be the user's picture directory
'ChDrive ThisWorkbook.Path
'ChDir ThisWorkbook.Path
ChDir Environ("USERPROFILE") & "\Pictures"
ChDrive Environ("USERPROFILE") & "\Pictures"

Can we bypass the call for the local directory and stick with the Getopenfilename portion?
 
Last edited:
Upvote 0
Ok. You are going to kill me for all of those posts but I am really trying to learn.

So the issue is that I was running it on my Mac so that is why the directive to look at my pictures in the normal Windows location was causing it to fail. Is that correctable since I work on both platforms? I run my QC checks for these techs at my office (mac) and when I work out in the field I use my PC.

Also, I was able to select a picture and put it in the cell but when I click to enlarge I am getting

"Cannot run the macro "TogglePict'. The macros may not be available in this workbook or all macros might be disabled"
 
Upvote 0
You Could uses something like the below:
Code:
<code>If InStr(1, Application.OperatingSystem, "Windows") > 0 Then
path = "blah"
Else
Path = "Blah"
End IF</code>
 
Upvote 0
something like this:
Code:
Option Explicit

Private Declare Function SetCurrentDirectoryA Lib "kernel32" _
    (ByVal lpPathName As String) As Long

Const bKeepPixAspectRatio As Boolean = True

'Add the Private Sub below to all worksheets where you want to insert pictures
'When a cell is right-clicked the code to insert a photo will be triggered
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
    InsertPictureIntoSelectedCell
End Sub
'End Add the Private Sub

'https://www.mrexcel.com/forum/excel-questions/1039443-inserting-resizing-pics.html

Sub InsertPictureIntoSelectedCell()
    'Assumes original picture size is larger than the cell size
    'Assumes original aspect ration should be retained
    
    Dim sCellAddr As String
    Dim sngCellHeight As Single
    Dim sngCellWidth As Single
    Dim sngPixHeight As Single
    Dim sngPixWidth As Single
    Dim sFilePathNameExt As String
    Dim sFilePath As String
    Dim sFileNameExt As String
    
    If Selection.Cells.Count > 1 Then
        MsgBox "Select the single cell where the picture will be inserted.", , "Select 1 Cell"
        GoTo End_Sub
    End If
    
    sngCellHeight = Selection.Height
    sngCellWidth = Selection.Width
    sCellAddr = Selection.Address(False, False)
    
    'Select File to Import
    
    Dim sFileName As String
    Dim sFileExt As String
    Dim vInput As Variant
    Dim vProcess() As String
    Dim lInputCount As Long
    Dim lFileIndex As Long
    Dim lFinalPathSepLoc As Long
    Dim s1Input As String
    Dim sServer As String
    Dim sIniPath As String
    Dim sFullPathFileName As String
    Dim lSuccess As Long
    Const bMultiSelect As Boolean = False
    Dim sngRatioToFit As Single
    
    sIniPath = CurDir
    
    'Set location that the directory search should start
    If InStr(1, Application.OperatingSystem, "Windows") > 0 Then
If ThisWorkbook.Path = vbNullString Then
ChDir Environ("USERPROFILE") & "\Pictures\"
ChDrive Environ("USERPROFILE") & "\Pictures\"
Else
If Left(ThisWorkbook.Path, 2) = "\\" Then
lSuccess = SetCurrentDirectoryA(ThisWorkbook.Path)
If lSuccess = 0 Then MsgBox "Unable to connect to " & vbLf & vbLf & _
sServer: Exit Sub
Else
'Change ThisWorkbook.Path in next 2 statements to environ("USERPROFILE") & "\Pictures\" if
' The initial image directory should be the user's picture directory
'ChDrive ThisWorkbook.Path
'ChDir ThisWorkbook.Path
ChDir Environ("USERPROFILE") & "\Pictures\"
ChDrive Environ("USERPROFILE") & "\Pictures\"

End If
End If

Else 'put code her to set MAC Directory location sorry i can help with this bit, as i have never worked with macs.

End If
    
    vInput = True
    'Open the standard Open dialog box at the specified location
    vInput = Application.GetOpenFilename("All Files (*.*), *.*", _
        , "Select a picture file to insert into the selected cell", "Only Mac Button Face", bMultiSelect)
        'If Cancel is selected vInput is always False
        'With MS True when one or more files are selected vInput is an array
        'With MS False when one file is selected vInput is a string
        
    On Error Resume Next  'Will cause an error if nothing selected
    If vInput <> False Then
        sFilePathNameExt = vInput
        On Error GoTo 0
            s1Input = sFilePathNameExt
            lFinalPathSepLoc = InStrRev(s1Input, Application.PathSeparator)
            sFilePath = CStr(Left(s1Input, lFinalPathSepLoc))
            sFileNameExt = CStr(Mid(s1Input, lFinalPathSepLoc + 1))
            sFileName = Left(sFileNameExt, InStr(sFileNameExt, ".") - 1)
            sFileExt = Mid(sFileNameExt, InStr(sFileNameExt, ".") + 1)
            
            '(Do stuff here with each filename in loop)

        'Next
    Else
        'User cancelled image selection
        GoTo End_Sub
    End If
    On Error GoTo 0
    
    
    ActiveSheet.Pictures.Insert(sFilePathNameExt).Select
    
    If bKeepPixAspectRatio Then
        
        If Selection.Height / sngCellHeight > Selection.Width / sngCellWidth Then
            sngRatioToFit = sngCellHeight / Selection.Height
        Else
            sngRatioToFit = sngCellWidth / Selection.Width
        End If
        Selection.ShapeRange.LockAspectRatio = msoTrue
        Selection.ShapeRange.ScaleHeight sngRatioToFit, msoFalse, msoScaleFromTopLeft

    Else
        Selection.ShapeRange.LockAspectRatio = msoFalse
        Selection.Height = sngCellHeight
        Selection.Width = sngCellWidth
    End If
    
    Selection.OnAction = "TogglePict"
    Selection.Name = sCellAddr
    
End_Sub:

End Sub


Sub TogglePict()
    'Assumes the original picture size is larger than the cell size
    
    Dim sName As String
    Dim sCellAddr As String
    
    Dim sngCellHeight As Single
    Dim sngCellWidth As Single
    Dim sngCellRatio As Single
    
    Dim sngPixHeight As Single
    Dim sngPixWidth As Single
    Dim sngPixRatio As Single
    
    Dim sngOrigPixHeight As Single
    Dim sngOrigPixWidth As Single
    Dim sngOrigPixRatio As Single
    
    Dim sngRatioToFit As Single
    
    sName = Application.Caller
    
    sngOrigPixHeight = ActiveSheet.Shapes(sName).Height
    sngOrigPixWidth = ActiveSheet.Shapes(sName).Width
    sngOrigPixRatio = sngOrigPixHeight / sngOrigPixWidth
    
    sngCellHeight = Range(sName).Height
    sngCellWidth = Range(sName).Width
    sngCellRatio = sngCellHeight / sngCellWidth
    
    If sngOrigPixHeight <= sngCellHeight And sngOrigPixWidth <= sngCellWidth Then
        'Picture is shrunk in the cell, so enlarge it and center it
        ActiveSheet.Shapes(sName).LockAspectRatio = msoFalse
        sngPixHeight = ActiveSheet.Shapes(sName).ScaleHeight(1, msoTrue)
        sngPixWidth = ActiveSheet.Shapes(sName).ScaleWidth(1, msoTrue)
        ActiveSheet.Shapes(sName).LockAspectRatio = msoTrue
        
        ActiveSheet.Shapes(sName).Left = (ActiveWindow.Width - ActiveSheet.Shapes(sName).Width) / 2
        ActiveSheet.Shapes(sName).Top = (ActiveWindow.Height - ActiveSheet.Shapes(sName).Height) / 2
        ActiveSheet.Shapes(sName).ZOrder msoBringToFront
    Else
        'Picture is out of the cell and needs to be put into it
        If bKeepPixAspectRatio Then
            
            If ActiveSheet.Shapes(sName).Height / sngCellHeight > ActiveSheet.Shapes(sName).Width / sngCellWidth Then
                sngRatioToFit = sngCellHeight / ActiveSheet.Shapes(sName).Height
            Else
                sngRatioToFit = sngCellWidth / ActiveSheet.Shapes(sName).Width
            End If
            ActiveSheet.Shapes(sName).LockAspectRatio = msoTrue
            ActiveSheet.Shapes(sName).ScaleHeight sngRatioToFit, msoFalse, msoScaleFromTopLeft
        Else
            ActiveSheet.Shapes(sName).ShapeRange.LockAspectRatio = msoFalse
            ActiveSheet.Shapes(sName).Height = sngCellHeight
            ActiveSheet.Shapes(sName).Width = sngCellWidth
        End If
        ActiveSheet.Shapes(sName).Left = Range(sName).Left
        ActiveSheet.Shapes(sName).Top = Range(sName).Top
        ActiveSheet.Shapes(sName).ZOrder msoSendToBack
        
    End If
    
    Application.ScreenUpdating = True
    
    
End Sub
 
Upvote 0

Forum statistics

Threads
1,223,228
Messages
6,170,871
Members
452,363
Latest member
merico17

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top