Pictures in Excel Add-in complete reference with code example

Pictures in Excel Add-in complete reference with code example


Refers to external graphical contents which you would like to bring into your Excel sheet for better data presentation. Pictures are useful objects to decorate or represent data in Excel. In this article I will show you how you can write a peace of code to bring a picture stored somewhere in hard drive in your Excel sheet.

VBA code example

Public Sub InsertPictureExample()
    'Declare sheet object
    Dim oSheet As Worksheet
    'Bind activesheet reference
    Set oSheet = ActiveSheet
    'Object to hold Picture
    Dim oPicture
    'Insert picture
    Set oPicture = oSheet.Pictures.Insert("C:\Users\Pictures\1-6.jpg")
    'Select picture
    'print width and height
    Debug.Print oPicture.Width
    Debug.Print oPicture.Height
    If Not oPicture Is Nothing Then
        Set oPicture = Nothing
    End If
    If Not oSheet Is Nothing Then
        Set oSheet = Nothing
    End If
End Sub

C# code example

private void btnInsertPicture_Click(object sender, RibbonControlEventArgs e)
	var fileContent = string.Empty;
	var filePath = string.Empty;
	//Open file dialog
	using (OpenFileDialog openFileDialog = new OpenFileDialog())
		openFileDialog.InitialDirectory = "c:\\";
		openFileDialog.Filter = "All Pictures (*.*)|*.*";
		openFileDialog.FilterIndex = 2;
		openFileDialog.RestoreDirectory = true;

		if (openFileDialog.ShowDialog() == DialogResult.OK)
			//Get the path of specified file
			filePath = openFileDialog.FileName;
			//Get worksheet
			excel.Worksheet oWorksheet = Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet;
			//get all pictures in a collection
			excel.Pictures oPictures = oWorksheet.Pictures();
			//add picture into collection

In above code I have used standard FileOpen dialog so user can browse through the file of his own choice.



Next >> Dynamic validation list in Excel with code example

Leave a Reply

Your email address will not be published.