使用VBA Exceldynamic最大Y轴缩放?

我不确定如何在VBA中为使用以下数据表创build的条形图设置Y轴最大值: 在这里输入图像说明

数据表将会dynamic变化(更多function或更less的function),所以我想Y轴最大值被设置为比Total的最大值大1的值。 另外, Total列也可能在其位置上发生变化,所以我无法将其设置为Total列的最大值。

我目前的条形码代码如下:

 Sub Create_BarChart() Range("A2").Select Dim lastColumn As Long lastColumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column Range(ActiveCell, Cells(ActiveCell.End(xlDown).Row, ActiveCell.End(xlToRight).Column)).Select ActiveSheet.Shapes.AddChart.Select ActiveChart.ChartType = xlColumnStacked ActiveChart.PlotBy = xlColumns ActiveChart.SetElement (msoElementDataLabelCenter) ' Format the data labels of the Total ActiveChart.SeriesCollection("Total").Format.Fill.Visible = msoFalse ActiveChart.SeriesCollection("Total").DataLabels.Font.Bold = True ActiveChart.SeriesCollection("Total").DataLabels.Select ActiveChart.Legend.LegendEntries(1).Font.Bold = True Selection.Position = xlLabelPositionInsideBase ' Set the maximum and minimum values of the y-axis ' ActiveChart.Axes(xlValue).MaximumScale = Application.WorksheetFunction.(Columns(lastColumn)) ActiveChart.Axes(xlValue).MinimumScale = 0 ActiveChart.Axes(xlValue).MaximumScale = ????????????????? ' Change the size of the Chart Dim Chart As ChartObject For Each Chart In ActiveSheet.ChartObjects With Chart.Parent ' change the numbers in the below brackets (5) to change the size of the chart. Here we are using inches to set the chart size. Chart.Height = Application.InchesToPoints(2.5) Chart.Width = Application.InchesToPoints(5) End With Next End Sub 

在这里输入图像说明

在代码的开头写下以下几行:

 Range("A2").Select Dim lastColumn As Long, lastRow As Long, max As Long lastRow = Cells(Rows.Count, "A").End(xlUp).Row lastColumn = ActiveSheet.Cells(2, Columns.Count).End(xlToLeft).Column max = WorksheetFunction.max(Range(Cells(3, lastColumn), Cells(lastRow, lastColumn))) 

这会给你max的总数,然后你可以写:

 ActiveChart.Axes(xlValue).MaximumScale = max + 1