I created a specific function to format my charts. The main Sub and the Function code:
Private Sub UserForm_Initialize()
Dim mychart As Chart
Dim ChartData As Range
Dim ChartName As String
Dim thiswb As Workbook
Dim imageName As String
Dim nColunas As Long
Dim i, j, k As Integer
Set thiswb = ThisWorkbook
k = 0
With thiswb.Sheets(4)
MultiPage1.Pages.Add
MultiPage1.Pages(k - 1).Controls.Copy
MultiPage1.Pages(k).Paste
Set ChartData = .Range("B2:B97")
Set mychart = .Shapes.AddChart(xlXYScatterLines).Chart
For j = mychart.SeriesCollection.Count To 1 Step -1
If j = 1 Then
Exit For
End If
mychart.SeriesCollection(j).Delete
Next j
mychart.SeriesCollection(1).Values = ChartData
mychart.SeriesCollection(1).XValues = .Range(.Cells(2, 1), .Cells(97, 1))
formatchart mychart
With .Shapes(1).Chart.Axes(xlCategory)
.MinimumScale = 0
.MaximumScale = 1
End With
imageName = Application.DefaultFilePath & Application.PathSeparator & "GraficoTemp.gif"
mychart.Export Filename:=imageName, FilterName:="GIF"
.Shapes(1).Delete
UserForm2.MultiPage1.Pages(k).Caption = "Total"
UserForm2.Controls("Image" & k + 1).Picture = LoadPicture(imageName)
Kill imageName
With Controls("Listbox" & k + 1)
.RowSource = "Total!B2:B97"
End With
End With
End Sub
Function formatchart(mychart As Chart)
With mychart
.HasTitle = False
.Legend.LegendEntries(1).Delete
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Caption = "Horas"
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Potência (W)"
End With
With mychart.Parent
.Height = 295
.Width = 470
.Top = 100
.Left = 100
End With
End Function
As you can see, the first thing the "formatchart" function does is remove the chart title. What happens is, when I run the complete Sub by pressing F5, the title is not removed. But when I debug it by pressing F8, I follow all the steps of the Sub till the end and the title ends up being removed!
What could be happening?
Having reconstructed the scenario on my computer with the complete code the following two things made your code work for me:
(1) Change the function into a sub and (2) pass the
ChartObject
to the sub instead ofChart
.So, following this you'll have to
and the initial setup will slightly change to
Instead of
you'll have to call the procedure like so
while changing the function to a procedure
I believe the problem is that you are adding a
Chart
according to your variable declaration but aShape
when looking at your original code above:I am not sure yet why the function didn't work and had to be a procedure instead. So, since I don't fully comprehend the problem yet I can only offer what seems to work here. If this doesn't help then let's hope that someone else comes up with a more conclusive solution.