这是我的excel数据
A 列:测试1、测试2、测试3、测试4、测试5、测试6、测试7、测试8、测试9、测试10、测试11
B 列:1,1,1,1,1,1,1,0,1,0,1
我想用下面的 VBA 代码创建图表
Sub createChart()
Dim ws As Worksheet
Dim chartObj As ChartObject
Dim testNames As Range, results As Range, chartData As Range
Dim anchorCell As Range
Set ws = ThisWorkbook.Sheets("Sheet1")
Set testNames = ws.Range("A2:A" & ws.Cells(ws.Rows.Count, 1).End(xlUp).Row)
Dim categoryValues As Variant
categoryValues = testNames.Value
Set results = ws.Range("B2:B" & ws.Cells(ws.Rows.Count, 1).End(xlUp).Row)
Set chartData = ws.Range("A1:B" & ws.Cells(ws.Rows.Count, 1).End(xlUp).Row)
' Set anchor cell to Q2 to determine chart position
Set anchorCell = ws.Range("Q2")
Set chartObj = ws.ChartObjects.Add(Left:=anchorCell.Left, Top:=anchorCell.Top, Width:=1320, Height:=724)
With chartObj.chart
.ChartType = xlLineMarkers
.SetSourceData Source:=chartData
.HasLegend = False
.chartTitle.Text = "GGG"
If IsArray(categoryValues) Then
' Multiple categories
.Axes(xlCategory).CategoryNames = categoryValues
Else
' Only one category, convert scalar to array
.Axes(xlCategory).CategoryNames = Array(categoryValues)
End If
With .Axes(xlValue)
.MinimumScale = 0
.MaximumScale = 1
.MajorUnit = 1
.CrossesAt = 0
End With
With .SeriesCollection(1)
.MarkerStyle = xlMarkerStyleCircle
.MarkerSize = 8
.MarkerBackgroundColor = RGB(0, 0, 255)
.MarkerForegroundColor = RGB(0, 0, 255)
.Format.Line.Visible = msoFalse
End With
End With
End Sub
但我尝试在 0 和 1 之间调整宽度。但它不是 y 轴的中间
我的预期结果根据我附加的图像在此处输入图像描述
我将0和1之间的宽度调整到中间的逻辑是下面的代码
With .Axes(xlValue)
.MinimumScale = -1
.MaximumScale = 2
.MajorUnit = 1
.CrossesAt = -1
End With
但它几乎可以工作,但根据我的第二张图片显示 2 和 -1 在此处输入图像描述。如何只显示1和0?
这不是解决方案,而是解决方法。
如果您不想在
2
轴上显示值 Y
,您可以将值限制为例如1.9
。-1
,您可以使用轴编号格式来隐藏负数。
With .Axes(xlValue)
.MinimumScale = -1
.MaximumScale = 1.9
.MajorUnit = 1
.CrossesAt = -1
.TickLabels.NumberFormat = "0;;0"
End With