我不确定如何在VBA中为使用以下数据表创建的条形图设置Y轴最大值:
数据表将动态变化(更多功能或更少功能),因此我希望将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
答案 0 :(得分:2)
在代码的开头写下以下几行:
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