Welcome to Excel Avon
How to Fit Pictures in a cell
DOWNLOAD USED EXCEL FILE FROM HERE>>
Today’s article is about fit pictures in a cell using VBA, today we are going to understand how to fit pictures in a cell with the help of excel vba, today how do we fit a picture in a cell.
Well, we’ll Fit the photo into Excel, and then Excel VBA, to Fit a pictures in a cell, we have to go like last time, first go to the Developer Tab, then we will click on the Visual Basic option as shown in the image below.
On opening in VBE, you have to go to Insert and then Module has to be inserted, as can be seen in the image.
To insert a picture in a cell using Excel VBA, we will write the FitImage subroutine in Excel VBA after inserting the module in VBE.
Sub FitImage() End Sub
After writing the subroutine we will define the variable
Sub FitImage() Dim Img as Picture Dim Cell as Range End Sub
Now we will create a condition using the TypeName function which will be something like this ‘if picture is not selected while running the macro’ we will get a message box which will have a message like this ‘please select only pictures. With this we will also use vbexclamation.
Sub FitImage() Dim Img as Picture Dim Cell as Range If TypeName (Selection)<>"Picture" Then Msgbox "please select Only Picture" vbexclaimation Exit Sub End If End Sub
Now we will use set for the image inserted in the worksheet.
Sub FitImage() Dim Img as Picture Dim Cell as Range If TypeName (Selection)<>"Picture" Then Msgbox "please select Only Picture" vbexclaimation Exit Sub End If Set Img = Selection End Sub
We want to fit picture in top left cell
Sub FitImage() Dim Img as Picture Dim Cell as Range If TypeName (Selection)<>"Picture" Then Msgbox "please select Only Picture" vbexclaimation Exit Sub End If Set Img = Selection set cell = img.TopLeftCell End Sub
Finally, we’ll set the attributes of the image.
Sub FitImage() Dim Img as Picture Dim Cell as Range If TypeName (Selection)<>"Picture" Then Msgbox "please select Only Picture" vbexclaimation Exit Sub End If Set Img = Selection set cell = img.TopLeftCell Img.Top = Cell.Top Img.Left = Cell.Left Img.Width= Cell.Width Img.Height= Cell.Height End Sub
After writing code in VBE, we will go back to excel sheet and then run more macro
After running the macro, if the picture is not selected, we will get a message box like this
Before running the macro, we will select the picture and then run the macro.
Now we can see that the fit picture in a cell
We have learned to fit the pictures in the cell.
So, I hope you have understood How to Fit pictures in a cell using Excel VBA macro and for more information, you can follow us on Twitter, Instagram, LinkedIn, and YouTube as well.
DOWNLOAD USED EXCEL FILE FROM HERE>>
You can also see well-explained video here about Fit picture in a cell using VBA