我正在尝试使用VBA和Excel自动生成折线图,其中每个数据点都有不同大小的误差条。 (我很想使用我的Python / matplotlib,但出于商业原因而被捆绑)
我尝试录制宏以查看如何操作,但生成的代码是:
Range("C2:C8").Select
ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range("'Sheet1'!$C$2:$C$8")
ActiveChart.ChartType = xlLineMarkers
ActiveChart.SeriesCollection(1).XValues = "='Sheet1'!$B$2:$B$8"
ActiveChart.PlotArea.Select
ActiveChart.SeriesCollection(1).HasErrorBars = True
ActiveSheet.ChartObjects("Chart 2").Activate
ActiveChart.SeriesCollection(1).ErrorBars.Select
ActiveChart.SeriesCollection(1).ErrorBar Direction:=xlY, Include:=xlBoth, _
Type:=xlCustom, Amount:=0
ActiveSheet.ChartObjects("Chart 2").Activate
ActiveChart.SeriesCollection(1).ErrorBars.Select
但这不太有用 - 金额值为零! 因此,我尝试将其更改并将其放入子例程中,使错误栏范围动态,如下所示:
Sub ErrorLine(sheetName As String, row1 As Integer, _
row2 As Integer, xcol As Integer, ycol As Integer, errCol As Integer)
Dim strErrorY As String
strErrorY = "=" & sheetName & "!" & _
Range(Cells(row1, errCol), Cells(row2, errCol)).Address()
Sheets(sheetName).Activate
Sheets(sheetName).Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range(Cells(row1, ycol), Cells(row2, ycol))
ActiveChart.ChartType = xlLineMarkers
With ActiveChart.SeriesCollection(1)
.XValues = Range(Cells(row1, xcol), Cells(row2, xcol))
.HasErrorBars = True
.ErrorBars.Select
.ErrorBar Direction:=xlY, Include:=xlBoth, _
Type:=xlCustom, Amount:=strErrorY, MinusValues:= _
strErrorY
End With
End Sub
但这只是给我一个折线图,没有误差条。谁能帮我吗? 帮助赞赏。
答案 0 :(得分:1)
.ErrorBar
似乎不喜欢A1样式地址,这是.Address
方法返回的内容。它喜欢RC风格的地址。
我的建议是:忘记字符串连接业务来制作单元格地址。它太乱了,真是太痛苦了!
只需自己提供范围。
Dim rngAmount As Range
Set rngAmount = _
Worksheets(sheetName).Range(Cells(row1, errCol), Cells(row2, errCol))
然后
Amount:=rngAmount, MinusValues:=rngAmount