Chart in Userform

User avatar
Joseph
3StarLounger
Posts: 206
Joined: 31 Dec 2010, 22:23
Location: Columbia Falls, MT

Chart in Userform

Post by Joseph »

I am currently attempting to execute some code from an Excel book, that is always wrong, so it seems.:

Save Chart1 as a GIF, then load it into a userform (NRPMH).

Here is the code that is not working, run time error '13'.

Code: Select all

Private Sub UserForm_Initialize()
Dim chart As chart
Dim fname As String
Dim ws As Worksheets
Set ws = Worksheets("Charts")
Application.ScreenUpdating = False
Set chart = ActiveSheet.Shapes.Chart1

'   Save chart as GIF
    fname = ThisWorkbook.Path & Application.PathSeparator & "temp.gif"
    chart.Export Filename:=fname, filterName:="GIF"
    Application.ScreenUpdating = True
    Chart1.Image1.Picture = LoadPicture(fname)
I'm hoping this is an easy fix.

User avatar
HansV
Administrator
Posts: 78493
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Chart in Userform

Post by HansV »

I very much doubt the code in the book really looked like that!

Try this version, and note that I made the indentation consistent. You should do the same right from the start, not as an afterthought.
I renamed the variable chart to cht since chart is also an Excel VBA keyword. It's best NOT to give a variable the name of a keyword.

Code: Select all

Private Sub UserForm_Initialize()
  Dim cht As chart
  Dim fname As String
  Application.ScreenUpdating = False
  Set cht = Worksheets("Charts").ChartObjects(1).Chart
  ' Save chart as GIF
  fname = ThisWorkbook.Path & Application.PathSeparator & "temp.gif"
  cht.Export Filename:=fname, FilterName:="GIF"
  Application.ScreenUpdating = True
  Me.Image1.Picture = LoadPicture(fname)
  Kill fname
End Sub
Best wishes,
Hans