不久前我做了这个子程序,因为我对 Excel 的图表自动缩放不满意。内置的 Excel 方法在一定程度上有效,但是当图表数据的范围变得更宽时,它只会将最小比例设置为 0,这可能会导致线条非常压扁,下方有大量空白空间。就像下面...
我编写的代码试图通过根据图表中的数据为 y 轴选择合适的最大和最小限制来改进 excel 的方法。它工作正常,但有时会选择不是最佳值。这是我的代码应用于同一图表的结果:
在这里,它已经适合绘图区域中的所有数据,因此可以很清楚地看到,但它选择的值并不是最好的。人类可以查看这些数据并快速评估 90 和 140 可能是在此示例中使用的最佳限制,但我在编写脚本来执行相同操作时遇到了麻烦。
这是整个子。时间不会太长。我很感激任何改进限制计算的建议......
Sub ScaleCharts()
'
' ScaleCharts Macro
'
Dim objCht As ChartObject
Dim maxi As Double, mini As Double, Range As Double, Adj As Double, xMax As Double, xMin As Double
Dim Round As Integer, Order As Integer, x As Integer, i As Integer
Application.ScreenUpdating = False
For x = 1 To ActiveWorkbook.Sheets.Count
Application.StatusBar = "Crunching sheet " & x & " of " & ActiveWorkbook.Sheets.Count
For Each objCht In Sheets(x).ChartObjects
If objCht.Chart.ChartType = xlLine Or objCht.Chart.ChartType = xlXYScatter Then
With objCht.Chart
For i = 0 To .SeriesCollection.Count - 1 'Loop through all the series in the chart
'Get the Max and Min values of the data in the chart
maxi = Application.max(.SeriesCollection(i + 1).Values)
mini = Application.min(.SeriesCollection(i + 1).Values)
Range = maxi - mini
If Range > 1 Then
Order = Len(Int(Range))
Adj = 10 ^ (Order - 2)
Round = -1 * (Order - 1)
ElseIf Range <> 0 Then
Order = Len(Int(1 / Range))
Adj = 10 ^ (-1 * Order)
Round = Order - 1
End If
'Get the Max and Min values for the axis based on the data
If i = 0 Or WorksheetFunction.Round(maxi, Round + 1) + Adj > xMax Then
xMax = WorksheetFunction.Round(maxi, Round + 1) + Adj
End If
If i = 0 Or WorksheetFunction.Round(mini, Round + 1) - Adj < xMin Then
xMin = WorksheetFunction.Round(mini, Round + 1) - Adj
End If
Next i
With .Axes(xlValue)
.MaximumScale = xMax
.MinimumScale = xMin
End With
End With
End If
Next objCht
Next x
Application.ScreenUpdating = True
Application.StatusBar = False
End Sub
编辑:这是 qPCR4vir 变化的结果......
最后 2 个图表被截断,因为它们不超过 -100