2016-11-22 69 views
0

我记录一个宏,而创建该图,生成:VBA定位一个Excel图表

Sub Macro13() 

    Columns("A:B").Select 
    ActiveSheet.Shapes.AddChart.Select 
    ActiveChart.SetSourceData Source:=Range("Sheet!$A$1:$B$100) 
    ActiveChart.ChartType = xlColumnClustered 
    ActiveChart.Legend.Select 
    Selection.Delete 
    ActiveChart.ChartTitle.Text = "Title" 
    'ActiveChart.Left = ActiveSheet.Cells(4, 4)  Doesnt work?? 
End Sub 

和我想在特定细胞中的曲线图的位置。然而,左()方法不会对ActiveChart工作,所有我找到了解决方案的线沿线的是哈克:

ActiveSheet.Graphs(0).Left() = 

我讨厌,因为我不想去猜测多少图表都在片。

有没有办法从上面创建图表时使用局部变量来定位图表? - 父是chartobject(图表容器)

ActiveChart.Parent.Left = Range("B2").Left 
ActiveChart.Parent.Top = Range("B2").Top 

ActiveChart是图表:这样的左上角是在范围B2

回答

4

这将移动您的图表对象。

0

这在回答你的最后一个问题:

有没有办法利用,当我创建上面的图表中一个局部变量的排行榜位置?

这合并了Darren's answer,同时帮助您根据工作表上的其他图表定位新图表。

Sub newChart() 

    Dim newChartPositionLeft As Integer 
    Dim newChartPositionTop As Integer 
    Dim lastChartAdded As ChartObject 
    Dim firstChart As Boolean 

    'Turn on error handling. If trying to access a previous chart fails, you know this is the first chart to be added 
    On Error Resume Next 
    Set lastChartAdded = ActiveSheet.ChartObjects(ActiveSheet.ChartObjects.Count) 
    If Err.Number <> 0 Then 
     firstChart = True 
    Else 
     firstChart = False 
     newChartPositionTop = lastChartAdded.Top + lastChartAdded.Height + 5 'Increase this number to add padding between charts 
     newChartPositionLeft = lastChartAdded.Left 'Aligning the new chart with the previous one 
    End If 
    On Error GoTo 0 

    'Your original code 
    Columns("A:B").Select 
    ActiveSheet.Shapes.AddChart.Select 
    ActiveChart.SetSourceData Source:=Range("Sheet!$A$1:$B$100") 
    ActiveChart.ChartType = xlColumnClustered 
    ActiveChart.Legend.Select 
    Selection.Delete 

    'Positioning the new chart 
    If firstChart Then 
    ActiveChart.Parent.Left = Range("B2").Left 
    ActiveChart.Parent.Top = Range("B2").Top 
    Else 
    ActiveChart.Parent.Left = newChartPositionLeft 
    ActiveChart.Parent.Top = newChartPositionTop 
    End If 


End Sub