2011-07-13 66 views
0

我試圖使用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 

但這只是給了我一個折線圖,並沒有錯誤吧。誰能幫我嗎? 幫助讚賞。

回答

1

.ErrorBar似乎不喜歡A1風格的地址,這就是.Address方法返回的內容。它喜歡RC風格的地址。

我的建議是:忘記字符串連接業務來製作單元地址。這很混亂,這是一個痛苦!

只提供範圍本身。

Dim rngAmount As Range 
Set rngAmount = _ 
    Worksheets(sheetName).Range(Cells(row1, errCol), Cells(row2, errCol)) 

然後

Amount:=rngAmount, MinusValues:=rngAmount 
+0

太棒了。感謝您的幫助。 – samb8s