Laurie Blome
Laurie Blome

Reputation: 41

Excel VBA to paste jpeg picture in Chart

I am using excel 2013. This is the code I had tried and it is not working. Any suggestions on how to write the VBA to either use the jpeg file to fill the chart, or the picture I have already as a shape in the sheet called "picture 6" Thank you!!!

Sub PastePic()

ActiveSheet.ChartObjects("MainChart").Activate
ActiveChart.ChartArea.Format.Fill.UserPicture("S:\CAT\Everyone\Analyse\Kundeplattform\square.jpeg")

End Sub

Upvotes: 3

Views: 3973

Answers (3)

Billdr
Billdr

Reputation: 1579

I was able to resolve a similar issue by using the FQPN for the file path. So instead of filePath = "s:\path\file.png" I used filePath = "\\server\share\path\file.png".

Upvotes: 0

Siddharth Rout
Siddharth Rout

Reputation: 149335

If it is a network path that is creating a problem then you can consider option 1 which is based on Sam's answer. Else use option 2 if you want to use thee shape "picture 6".

OPTION 1)

Copy it to the local drive as Sam in his answer suggested. You can either manually copy it or do it via code.

This code will copy the image to user's temp directory from the network path and then use that as an image.

UNTESTED

Const sPath As String = "S:\blah\blah\Sample.jpg"

Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" _
(ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long

Private Const MAX_PATH As Long = 260

Sub Sample()
    Dim TempFile As String

    TempFile = TempPath & "Sample.Jpg"

    FileCopy sPath, TempFile

    DoEvents

    ActiveSheet.ChartObjects("MainChart").Activate
    ActiveChart.ChartArea.Format.Fill.UserPicture (TempFile)

    Kill TempFile
End Sub

Function TempPath() As String
    TempPath = String$(MAX_PATH, Chr$(0))
    GetTempPath MAX_PATH, TempPath
    TempPath = Replace(TempPath, Chr$(0), "")
End Function

OPTION 2)

Using the shape picture 6 which you already have in your Excel file.

You can use the example that I have shown HERE which uses .CopyPicture and Stephen Bullen's PastePicture Function

Upvotes: 0

StoriKnow
StoriKnow

Reputation: 5867

Your code looks fine and works for me.

It looks like you're retrieving the picture from your network. Try moving the picture to your C: drive on your local machine (i.e. C:\square.jpeg) and try the macro again, it may be a network issue.

Upvotes: 1

Related Questions