我创建了一个特定的函数来格式化我的图表。主要Sub和功能代码:
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
正如你所看到的,"格式图"功能确实是删除图表标题。会发生什么,当我按F5运行完整的Sub时,标题不会被删除。但是当我通过按F8调试它时,我按照Sub的所有步骤直到结束,标题最终被移除!
可能会发生什么?
答案 0 :(得分:2)
使用完整的代码在我的计算机上重建了这个场景,以下两件事使我的代码适合我:
(1)将功能更改为子和
(2)将ChartObject
传递给子而不是Chart
。
所以,接下来你必须
Dim mychart as ChartObject
并且初始设置将略微更改为
Set mychart = .ChartObjects.Add(295, 470, 100, 100)
mychart.Chart.ChartType = xlXYScatterLines
而不是
formatchart mychart
你必须像这样调用这个程序
Call formatchart(mychart)
将函数更改为过程
Sub formatchart(mychart As ChartObject)
With mychart.Chart
.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
.Height = 295
.Width = 470
.Top = 100
.Left = 100
End With
End Sub
我认为问题在于,根据您的变量声明添加Chart
,但在查看上面的原始代码时添加Shape
:
Set mychart = .Shapes.AddChart(xlXYScatterLines).Chart
我不确定为什么这个功能不起作用而必须成为一个程序。所以,既然我不能完全理解这个问题,那么我只能提供这里似乎有用的东西。如果这没有帮助,那么让其他人想出一个更具决定性的解决方案。