VBA定位一个excel图表

我在创build这个图的时候logging了一个macros,生成:

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 

我想在特定的单元格中定位graphics。 然而,Left()方法在ActiveChart上不起作用,我发现的所有解决scheme都是hacky:

 ActiveSheet.Graphs(0).Left() = 

我讨厌,因为我不想猜测工作表上有多less图表。

有没有办法从上面创build图表时使用局部variables来定位图表?

这将移动你的图表对象,所以左上angular在范围B2:

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

ActiveChart是图表 – 父图表是图表对象(图表的容器)。

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

有没有办法从上面创build图表时使用局部variables来定位图表?

这个结合了Darren的答案,同时帮助你根据表格上的其他图表定位新的图表。

  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