简体   繁体   English

PowerPoint / Excel VBA-更改图表的默认数据范围

[英]PowerPoint/Excel VBA - Change default range of data for a chart

I want to be able to use my own Excel Workbook to create a pie diagram in PowerPoint. 我希望能够使用自己的Excel工作簿在PowerPoint中创建饼图。 So far, I have created a VBA script to add the chart. 到目前为止,我已经创建了一个VBA脚本来添加图表。 I also changed the data sheet for the chart to look like this: Problem 我还更改了图表的数据表,使其看起来像这样: 问题

Following core problem remains: 以下核心问题仍然存在:

  • I can't figure out, how to dynamically define the data range of the chart's data source sheet 我不知道如何动态定义图表数据源表的数据范围

Because the default values for the pie chart belong to these ranges, PowerPoint sets those ranges by default. 由于饼图的默认值属于这些范围,因此PowerPoint会默认设置这些范围。 If my data sheet contains more (or equal to) than 4 rows of data, it won't be that bad, as the range automatically increases. 如果我的数据表包含的数据行数大于(或等于)4行,那么范围就不会那么大,因为范围会自动增加。 However, as shown in the example, the range doesn't adapt when there are only 3 rows of data. 但是,如示例中所示,当只有3行数据时,范围不适应。

What I want, would look like this: Needed (I only know how to get the data in the correct place, but not how to select it) 我想要的是这样的: 需要 (我只知道如何在正确的位置获取数据,但不知道如何选择)

Related VBA code is below: 相关的VBA代码如下:

Set diaPie = pres.Slides(3).Shapes.AddChart2(2, xlPie).Chart
Set pieChartData = diaPie.ChartData
Set pieWorkbook = pieChartData.Workbook
Set pieWorksheet = pieWorkbook.Worksheets(1)

pieWorksheet.UsedRange.Clear

With dataWorksheet
    id = .Cells(.Rows.Count, "A").End(xlUp).Row
End With

a = dataWorksheet.Range("A1", dataWorksheet.Range("A1").Offset(id, 0))
b = dataWorksheet.Range("B1", dataWorksheet.Range("B1").Offset(id, 0))


pieWorksheet.Range("A2", pieWorksheet.Range("A2").Offset(id, 0)) = a
pieWorksheet.Range("B2", pieWorksheet.Range("B2").Offset(id, 0)) = b

Thanks in advance! 提前致谢!

This should change the data range on your data sheet. 这将更改数据表上的数据范围。 maxrow is just the end of the data. maxrow只是数据的结尾。 So if your data is in B1:B4 then maxrow would be 4 因此,如果您的数据在B1:B4中,则maxrow为4

diaPie.SeriesCollection(1).values = "Sheet1!$B$1:$B" & maxrow  ' change the series range before opening and closing the workbook object
diaPie.SeriesCollection(1).XValues = "Sheet1!$A$1:$A" & maxrow  'Labels

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM