Compress images with vba code

kelly mort

Well-known Member
Joined
Apr 10, 2017
Messages
2,169
Office Version
  1. 2016
Platform
  1. Windows
HelloWorld,

I have the feeling there is a way to compress image files with a vba script. If anyone agrees to that can we take up that challenge?


Basically, I will be compressing from a folder. And will like the smallest size possible.

Say below 100kb .

Thanks in advance
Kelly
 

Excel Facts

Create a Pivot Table on a Map
If your data has zip codes, postal codes, or city names, select the data and use Insert, 3D Map. (Found to right of chart icons).
So I have been able to search and come across these codes.

I don't reallyunderstand them. But I have the feeling they can be tweaked to my needs. Can someone with that skills fix it for me? By compress I mean reduce in bytes not dimensions.

Thanks

Code:
Sub CompressPic()
Code:
[COLOR=#333333][FONT='inherit']    If TypeName(Selection) = "Picture" Then[/FONT][/COLOR]
[COLOR=#333333][FONT='inherit']        Application.SendKeys "%a~"[/FONT][/COLOR]
[COLOR=#333333][FONT='inherit']        Application.CommandBars.ExecuteMso "PicturesCompress"[/FONT][/COLOR]
[COLOR=#333333][FONT='inherit']    End If[/FONT][/COLOR]

[COLOR=#333333][FONT='inherit']End Sub

[/FONT][/COLOR]



Code:
Code:
][COLOR=#660066][FONT=inherit]Public[/FONT][/COLOR][COLOR=#660066][FONT=inherit]Sub[/FONT][/COLOR][COLOR=#660066][FONT=inherit]ResizeAndCompressSelectedImages[/FONT][/COLOR][COLOR=#666600][FONT=inherit]()[/FONT][/COLOR][COLOR=#000000][FONT=inherit]
    [/FONT][/COLOR][COLOR=#008800][FONT=inherit]'   Store selected images before we start '[/FONT][/COLOR][COLOR=#000000][FONT=inherit]
    [/FONT][/COLOR][COLOR=#660066][FONT=inherit]Dim[/FONT][/COLOR][COLOR=#000000][FONT=inherit] oShape [/FONT][/COLOR][COLOR=#660066][FONT=inherit]As[/FONT][/COLOR][COLOR=#660066][FONT=inherit]Shape[/FONT][/COLOR][COLOR=#000000][FONT=inherit]
    [/FONT][/COLOR][COLOR=#660066][FONT=inherit]Dim[/FONT][/COLOR][COLOR=#000000][FONT=inherit] cShapes [/FONT][/COLOR][COLOR=#660066][FONT=inherit]As[/FONT][/COLOR][COLOR=#660066][FONT=inherit]New[/FONT][/COLOR][COLOR=#660066][FONT=inherit]Collection[/FONT][/COLOR][COLOR=#000000][FONT=inherit]
    [/FONT][/COLOR][COLOR=#660066][FONT=inherit]For[/FONT][/COLOR][COLOR=#660066][FONT=inherit]Each[/FONT][/COLOR][COLOR=#000000][FONT=inherit] oShape [/FONT][/COLOR][COLOR=#660066][FONT=inherit]In[/FONT][/COLOR][COLOR=#660066][FONT=inherit]ActiveWindow[/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#660066][FONT=inherit]Selection[/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#660066][FONT=inherit]ShapeRange[/FONT][/COLOR][COLOR=#000000][FONT=inherit]
        [/FONT][/COLOR][COLOR=#660066][FONT=inherit]If[/FONT][/COLOR][COLOR=#000000][FONT=inherit] oShape[/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#660066][FONT=inherit]Type[/FONT][/COLOR][COLOR=#666600][FONT=inherit]=[/FONT][/COLOR][COLOR=#000000][FONT=inherit] msoPicture [/FONT][/COLOR][COLOR=#660066][FONT=inherit]Then[/FONT][/COLOR][COLOR=#000000][FONT=inherit] cShapes[/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#660066][FONT=inherit]Add[/FONT][/COLOR][COLOR=#000000][FONT=inherit] oShape
    [/FONT][/COLOR][COLOR=#660066][FONT=inherit]Next[/FONT][/COLOR][COLOR=#000000][FONT=inherit] oShape
    
    [/FONT][/COLOR][COLOR=#008800][FONT=inherit]'   Now, reduce the resolution of all of the selected
    '[/FONT][/COLOR][COLOR=#000000][FONT=inherit]   shapes[/FONT][/COLOR][COLOR=#666600][FONT=inherit],[/FONT][/COLOR][COLOR=#000000][FONT=inherit] one at a time
    [/FONT][/COLOR][COLOR=#660066][FONT=inherit]Dim[/FONT][/COLOR][COLOR=#000000][FONT=inherit] prevWidth [/FONT][/COLOR][COLOR=#660066][FONT=inherit]As[/FONT][/COLOR][COLOR=#660066][FONT=inherit]Single[/FONT][/COLOR][COLOR=#000000][FONT=inherit]
    [/FONT][/COLOR][COLOR=#660066][FONT=inherit]Dim[/FONT][/COLOR][COLOR=#000000][FONT=inherit] prevHeight [/FONT][/COLOR][COLOR=#660066][FONT=inherit]As[/FONT][/COLOR][COLOR=#660066][FONT=inherit]Single[/FONT][/COLOR][COLOR=#000000][FONT=inherit]
    [/FONT][/COLOR][COLOR=#660066][FONT=inherit]For[/FONT][/COLOR][COLOR=#660066][FONT=inherit]Each[/FONT][/COLOR][COLOR=#000000][FONT=inherit] oShape [/FONT][/COLOR][COLOR=#660066][FONT=inherit]In[/FONT][/COLOR][COLOR=#000000][FONT=inherit] cShapes
        prevWidth [/FONT][/COLOR][COLOR=#666600][FONT=inherit]=[/FONT][/COLOR][COLOR=#000000][FONT=inherit] oShape[/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#000000][FONT=inherit]width[/FONT][/COLOR][COLOR=#666600][FONT=inherit]:[/FONT][/COLOR][COLOR=#000000][FONT=inherit] prevHeight [/FONT][/COLOR][COLOR=#666600][FONT=inherit]=[/FONT][/COLOR][COLOR=#000000][FONT=inherit] oShape[/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#000000][FONT=inherit]height
        oShape[/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#660066][FONT=inherit]LockAspectRatio[/FONT][/COLOR][COLOR=#666600][FONT=inherit]=[/FONT][/COLOR][COLOR=#000000][FONT=inherit] msoTrue
        oShape[/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#000000][FONT=inherit]width [/FONT][/COLOR][COLOR=#666600][FONT=inherit]=[/FONT][/COLOR][COLOR=#006666][FONT=inherit]40[/FONT][/COLOR][COLOR=#008800][FONT=inherit]'   Something small '[/FONT][/COLOR][COLOR=#000000][FONT=inherit]
        oShape[/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#660066][FONT=inherit]Copy[/FONT][/COLOR][COLOR=#000000][FONT=inherit]
        [/FONT][/COLOR][COLOR=#660066][FONT=inherit]ActiveWindow[/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#660066][FONT=inherit]View[/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#660066][FONT=inherit]PasteSpecial[/FONT][/COLOR][COLOR=#000000][FONT=inherit] ppPastePNG
        [/FONT][/COLOR][COLOR=#660066][FONT=inherit]With[/FONT][/COLOR][COLOR=#660066][FONT=inherit]ActiveWindow[/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#660066][FONT=inherit]Selection[/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#660066][FONT=inherit]ShapeRange[/FONT][/COLOR][COLOR=#666600][FONT=inherit]([/FONT][/COLOR][COLOR=#006666][FONT=inherit]1[/FONT][/COLOR][COLOR=#666600][FONT=inherit])[/FONT][/COLOR][COLOR=#000000][FONT=inherit]
            [/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#660066][FONT=inherit]Left[/FONT][/COLOR][COLOR=#666600][FONT=inherit]=[/FONT][/COLOR][COLOR=#000000][FONT=inherit] oShape[/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#660066][FONT=inherit]Top[/FONT][/COLOR][COLOR=#666600][FONT=inherit]=[/FONT][/COLOR][COLOR=#000000][FONT=inherit] oShape[/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#660066][FONT=inherit]Top[/FONT][/COLOR][COLOR=#000000][FONT=inherit]
            [/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#000000][FONT=inherit]width [/FONT][/COLOR][COLOR=#666600][FONT=inherit]=[/FONT][/COLOR][COLOR=#000000][FONT=inherit] prevWidth[/FONT][/COLOR][COLOR=#666600][FONT=inherit]:[/FONT][/COLOR][COLOR=#000000][FONT=inherit]
            [/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#000000][FONT=inherit]height [/FONT][/COLOR][COLOR=#666600][FONT=inherit]=[/FONT][/COLOR][COLOR=#000000][FONT=inherit] prevHeight
        [/FONT][/COLOR][COLOR=#660066][FONT=inherit]End[/FONT][/COLOR][COLOR=#660066][FONT=inherit]With[/FONT][/COLOR][COLOR=#000000][FONT=inherit]
        oShape[/FONT][/COLOR][COLOR=#666600][FONT=inherit].[/FONT][/COLOR][COLOR=#660066][FONT=inherit]Delete[/FONT][/COLOR][COLOR=#000000][FONT=inherit]
    [/FONT][/COLOR][COLOR=#660066][FONT=inherit]Next[/FONT][/COLOR][COLOR=#000000][FONT=inherit] oShape
[/FONT][/COLOR][COLOR=#660066][FONT=inherit]End[/FONT][/COLOR][COLOR=#660066][FONT=inherit]Sub
[/FONT][/COLOR]
 
Upvote 0
This is the code that loads the images. So when I print the worksheet, (I print through a loop which can take up say 100 counters ) the file size grows . I have no idea why. That's why I need to compress image before run the loop. Thanks

Code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim fPath As String, sFile$
If Target = Me.[h9] Then
    fPath = ThisWorkbook.Path & "" & Me.CmbTerm.Text
    sFile = Dir(fPath & "" & Right(Me.[h9].Text, 3) & ".*")
    If sFile <> vbNullString Then
      Me.Image1.Picture = LoadPicture(fPath & "" & sFile)
    Else
        Me.Image1.Picture = LoadPicture("")
    End If
    If Err.Number = 53 Then Me.Image1.Picture = LoadPicture("")
End If
End Sub
 
Upvote 0
HelloWorld,

I have the feeling there is a way to compress image files with a vba script. If anyone agrees to that can we take up that challenge?


Basically, I will be compressing from a folder. And will like the smallest size possible.

Say below 100kb .

Thanks in advance
Kelly

I sorted image file size compression last summer, took me 8 months to write. I have to get files under 4MB for uploading to a client database all day.

I've added some code before the macro, so a MsgBox appears briefly at the end, I use this MsgBox active window text in a Log Macro in Excel, which records all active windows text.

I have a copy of this macro as macro c lowercase with the SendKeys as E for 96ppi.

Currently I'm trying to simplify the macro by detecting Compression options: "Apply only to this picture" and always ensure it is unticked. I couldn't work this out, so my loop of all images will either apply to that image selected, or all images. I want to save time and not loop through all of them. Stumped me still.


Private Declare PtrSafe Function CustomTimeOffMsgBox Lib "user32" Alias "MessageBoxTimeoutA" ( _
ByVal xHwnd As LongPtr, _
ByVal xText As String, _
ByVal xCaption As String, _
ByVal xMsgBoxStyle As VbMsgBoxStyle, _
ByVal xwlange As Long, _
ByVal xTimeOut As Long) _
As Long 'See SOURCE below


Sub MacroC_22_02_2023()

theState = Application.NumLock 'Mad, my external Trust USB Numberpad states False when
'hovering over Application.Numberlock via Fn+F8 and stepped past
'but says False when the numberpad is on!

'150ppi
Word.Application.ScreenUpdating = False 'doesn't work with SendKeys workarounds for no direct coding availability

'No explicit Source for creating this by jam61mar@gmail.com, james.martin@birmingham.gov.uk
'Macro "C" to compress images in Word if docx file size is too big
'Tip for adding [wait] after the sendkeys SendKeys statement (VBA)

'If Macro C is pressed in error with no file in Open Word App
If Word.Application.Documents.Count = 0 Then
Exit Sub
End If

Dim oIlS As inlineshape

If Word.ActiveDocument.InlineShapes.Count > 0 Then

'Select the first image so that the "Picture Format" Ribbon Menu appears
Word.ActiveDocument.InlineShapes(1).Select

'150ppi - this is counter intuitive as it appears before the menu
VBA.SendKeys "%W{ENTER}", True
'Opens the "Compress Pictures" Sub Menu on Picture Format
'A different version appears if the above Select 1st image line is switched off, so that line is critical for the actual sub menu
Application.CommandBars.ExecuteMso ("PicturesCompress") '20-05-2022 Can add brackets around the speach marks

DoEvents '''28/06/2022 Add SendKeys for a 2nd time each time used to undo toggling off the NumLock
'''VBA SendKeys (F2) and NumLock Issue
'150ppi - this is counter intuitive as it appears before the menu
VBA.SendKeys "%W{ENTER}", True
Application.CommandBars.ExecuteMso ("PicturesCompress")


'Timer function (Visual Basic for Applications)
'for a delay to stop the Commandbar sub menu from flickering too much, still prefer to not see it
Dim PauseTime, Start, Finish, TotalTime
PauseTime = 0
Start = Timer
Do While Timer < Start + PauseTime
DoEvents
Loop
Finish = Timer
TotalTime = Finish - Start
Else
End


End If

'Restarting a loop for the rest of the images in the Active Document

For i = 2 To Word.ActiveDocument.InlineShapes.Count

If Word.ActiveDocument.InlineShapes.Count > 1 Then
Word.ActiveDocument.InlineShapes(i).Select

VBA.SendKeys "%W{ENTER}", True
Application.CommandBars.ExecuteMso ("PicturesCompress")

DoEvents '''2nd running to toggle numlock back on
VBA.SendKeys "%W{ENTER}", True
Application.CommandBars.ExecuteMso ("PicturesCompress")

'Timer function (Visual Basic for Applications)
'for a delay to stop the Commandbar sub menu from flickering too much, still prefer to not see it
'Dim PauseTime, Start, Finish, TotalTime
PauseTime = 0
Start = Timer
Do While Timer < Start + PauseTime
DoEvents
Loop
Finish = Timer
TotalTime = Finish - Start
Else
End

End If

Next i
'MsgBox appears briefly for 300 thousandths of a second, and Closes so Macro L detects the Macro C usage.
'SOURCE: https://wwwextendoffice.com/documents/excel/3836-excel-message-box-timer-timeout.html
Call CustomTimeOffMsgBox(0, "", "WORD MACRO C - Compress Image(s) to 150ppi", vbInformation, 0, 300)



Word.Application.ScreenUpdating = True

End Sub
 
Last edited by a moderator:
Upvote 0

Forum statistics

Threads
1,223,896
Messages
6,175,260
Members
452,627
Latest member
KitkatToby

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