VBA图表标题未填充

时间:2018-05-22 04:18:19

标签: excel vba excel-vba excel-charts

我有一个数据列表,我需要为每两行生成一个图表,并给出与第一行相关联的图表标题。数据示例如下:

Example

等等。

我用来创建图表的代码是:

Sub loopChart()

Dim mychart As Chart
Dim myRange As Range
Dim c As Integer
Dim r As Integer
Dim s As Integer
Dim ttl As String




r = 2
While r <= 10 '1=dataSource1, 4=dataSource2, 7=dataSource3
'set data source for the next chart

With Worksheets("Sheet9")
    Set myRange = .Range(.Cells(r, 2), .Cells(r + 1, 14))

End With
'create chart
Sheets("Chart").Select
    ActiveSheet.Shapes.AddChart.Select

    With ActiveChart
         ttl = Range("A" & r)
        .ChartType = xlLineMarkers 'xlLine
        .SetSourceData Source:=myRange, PlotBy:=xlRows  'sets source data for graph including labels
        .SetElement (msoElementLegendRight) 'including legend
        .HasTitle = True
        'dimentions & location:
        .Parent.Top = 244  'defines the coordinates of the top of the chart
        '.Parent.Left = r * 150  'defines the coordinates for the left side of the chart
        .Parent.Height = 200
        .Parent.Width = 300
        .ChartTitle.Formula = ttl
    End With

r = r + 2
Wend

End Sub

所以,生成的第一个图表应该在第2行得到标题,下一个图表应该有第4行的标题... 我总是在第一张图表上获得图表标题,但不会在任何其他图表上生成。有人可以帮我这个吗?

2 个答案:

答案 0 :(得分:1)

请在下面修复。

ttl = Range("A" & r)

ttl = Worksheets("Sheet9").Range("A" & r).Value

答案 1 :(得分:0)

我认为@Dy.Lee的答案可以解决问题,但要进一步说明:

尝试避免使用@model ProfileViewModel

建议的解决方法:

.select

您的代码会在同一位置创建每个图形,因此您只能看到一个(最后一个),因此Sub loopChart() Dim Ch As Chart Dim Sh1 As Worksheet: Set Sh1 = Sheets("Sheet9") Dim Sh2 As Worksheet: Set Sh2 = Sheets("Chart") Dim L As Integer L = 0 For i = 2 To 18 Step 2 Set Ch = Sh2.Shapes.AddChart.Chart Ch.SetSourceData Sh1.Range(Sh1.Cells(i, 2), Sh1.Cells(i + 1, 14)) Ch.ChartType = xlLineMarkers Ch.SetElement (msoElementLegendRight) Ch.HasTitle = True Ch.Parent.Top = 244 Ch.Parent.Height = 200 Ch.Parent.Width = 300 Ch.Parent.Left = L Ch.ChartTitle.Caption = Sh1.Cells(i, 1).Value L = L + 300 Next i End Sub 行具有可变值。