2017-04-04 44 views
1

編程折線圖他們給我一個任務,以編程方式生成以下圖表:在Excel

chart

到目前爲止,我發現這些使用VBA生成圖表的這些resourcesMSDN Docs

這是我當前的代碼:

Private Sub CommandButton1_Click() 
Sheet1.Select 
ActiveSheet.Shapes.AddChart.Select 
ActiveSheet.Shapes(1).Top = 10 
ActiveSheet.Shapes(1).Left = 10 
ActiveChart.ChartType = xlLineMarkers 

ActiveChart.PlotArea.Select 
ActiveChart.SetSourceData Source:=Range("Table1") 
ActiveChart.HasTitle = True 
ActiveChart.ChartTitle.Text = Sheet1.Range("B2").Value 
End Sub 

不過,我不太得到我需要的輸出。

這是一個例子的數據表:

My Sample Table

注:

  1. 橙色線 - 上和每個項目的下限。
  2. 藍色虛線 - 每個項目的值。
+3

正如我們所不知道你想要的輸出是什麼,你最好的辦法是記錄自己創造圖表。然後,您可以檢查該錄製的輸出並將其轉換爲有用/可重用的內容。 – CLR

+0

@CLR在我的第一句話。我修改了問題並提供了我需要輸出的超鏈接。 – Hexxed

+2

您是否嘗試錄製自己創建圖表? – CLR

回答

2

好吧,以下接近。您需要更改範圍(或將其設置爲動態查找它 - 這是另一個問題),併爲單元格標題的位置等設置單元格範圍,但我認爲這應該讓您繼續:

Excel 2013版本:

ActiveSheet.Shapes.AddChart2(332, xlLineMarkers).Select 
With ActiveChart 

    ' Set the source 
    .SetSourceData Source:=Range("Sheet1!$A$1:$D$6") 

    ' Set the title 
    .ChartTitle.Text = Sheet1.Range("B1").Value 

    ' Format the labels to 45 degrees 
    .Axes(xlCategory).TickLabels.Orientation = 45 

    ' Set Line 2 to Orange dash, no marker 
    With .FullSeriesCollection(2).Format.Line 
     .ForeColor.ObjectThemeColor = msoThemeColorAccent2 
     .DashStyle = msoLineDash 
     .Parent.Parent.MarkerStyle = -4142 
     'add other formatting here 
    End With 

    ' Set Line 3 to Orange dash, no marker 
    With .FullSeriesCollection(3).Format.Line 
     .ForeColor.ObjectThemeColor = msoThemeColorAccent2 
     .DashStyle = msoLineDash 
     .Parent.Parent.MarkerStyle = -4142 
     'add other formatting here 
    End With 

End With 

我通過記錄一個宏,然後加入在With以汽提出的.Activechart不必要的使用獲得這一點。你可以隨時Set它,如果你以後需要引用它,但是這又是一個問題。如果您想進一步細化,您也可以創建一個循環來取出.FullSeriesCollection()的其中一段代碼。

的Excel 2007/2010版本:(與循環和可視性的解決方法,使顏色變化)

ActiveSheet.Shapes.AddChart.Select 
With ActiveChart 
    .ApplyLayout (1) 
    .SetSourceData Source:=Range("'Sheet1'!$A$1:$D$6") 
    .ChartType = xlLineMarkers 
    .Axes(xlCategory).TickLabels.Orientation = 45 
    .ChartTitle.Text = Sheet1.Range("B1").Value 

    For scoln = 2 To 3 
     With .SeriesCollection(scoln) 
      .Format.Line.Visible = False 
      .Format.Line.Visible = True 
      .Format.Line.ForeColor.RGB = 683236 
      .Format.Line.DashStyle = msoLineSysDash 
      .MarkerStyle = -4142 
     End With 
    Next 

    With .SeriesCollection(1) 
     .MarkerStyle = 8 
     .MarkerSize = 8 
    End With 
End With 
+0

即時通過'.FullSeriesCollection'獲取錯誤 - >'找不到方法或數據成員' – Hexxed

+0

顯然在進一步研究(如果我正確理解它們的話)'AddChart2'和這個在Office 2013之後的'.FullSeriesCollection'上。我正在使用2010. – Hexxed

+1

我已經添加了一個與早期Office版本兼容的版本來解決我的問題。 – CLR