我试图通过vba选择连续数据输入图表。数据根据用户希望看到的年份而变化,因此可以向右或向右延伸。下面的第三行显示了我尝试选择相关范围的位置,但这会返回错误消息。我已经包含了其余的代码,以防我在最后一行上做了同样的错误。
Charts.Add
ActiveChart.ChartType = xlLineMarkers
ActiveChart.SetSourceData Source:=ActiveSheet.Range("F36", ActiveSheet.Range("F36").End(xlToRight)).Select, PlotBy:=xlRows
ActiveChart.Location Where:=xlLocationAsObject, Name:="Parameter Forecasts"
ActiveChart.HasTitle = True
ActiveChart.HasLegend = False
ActiveChart.Parent.Height = Range("E10:E34").Height
ActiveChart.Parent.Width = Range("E10:Y10").Width
ActiveChart.Parent.Top = Range("E10").Top
ActiveChart.Parent.Left = Range("E10").Left
ActiveChart.ChartTitle.Characters.Text = "=Parameter Forecasts!E37"
ActiveChart.Axes(xlCategory, xlPrimary).HasTitle = True
ActiveChart.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Year"
ActiveChart.Axes(xlValue, xlPrimary).HasTitle = False
ActiveChart.SeriesCollection.NewSeries.XValues = ActiveSheet.Range("F37", ActiveSheet.Range("F37").End(xlToRight)).Select
非常感谢, 最大
答案 0 :(得分:1)
定义Chart
类型变量/对象并将图表设置为它更容易,更安全。之后,您可以使用With
语句修改其所有属性。
如果您远离ActiveChart
,ActiveSheet
,而是使用引用的对象,那就更好了。
<强>代码强>
Option Explicit
Sub AutoChart()
Dim MyCht As Chart
Dim Sht1 As Worksheet
Dim ShtName As String
Set MyCht = Charts.Add
Set Sht1 = Worksheets("Sheet1") '<-- I suggest not tuse ActiveSheet , but the Sheet's name, like Worksheets("Sheet1")
ShtName = Sht1.Name '<-- this is where you will put your chart later
' not sure is the string below representes the worksheet's name you want to put your chart
'ShtName = "Parameter Forecasts"
With MyCht
.ChartType = xlLineMarkers
.SetSourceData Sht1.Range("F36", Sht1.Range("F36").End(xlToRight))
.PlotBy = xlRows
.Location where:=xlLocationAsObject, Name:=ShtName
' you can keep going setting the rest of your parameters
End With
End Sub
修改1 :更改为ChartObject
以帮助PO获得一些额外帮助
Option Explicit
Sub AutoChart()
Dim MyChtObj As ChartObject
Dim Sht1 As Worksheet
Dim ShtName As String
Set Sht1 = Worksheets("Parameter Forecasts") '<-- I suggest not tuse ActiveSheet , but the Sheet's name, like Worksheets("Sheet1")
ShtName = Sht1.Name '<-- this is where you will put your chart later
Set MyChtObj = Sht1.ChartObjects.Add(100, 100, 500, 500)
With MyChtObj
With .Chart
.ChartType = xlColumnClustered ' xlLineMarkers
.SetSourceData Sht1.Range("F36", Sht1.Range("F36").End(xlToRight))
.PlotBy = xlRows
' the line below is not need since using the ChartObject
'.Location where:=xlLocationAsObject, Name:=ShtName
.HasTitle = True
.ChartTitle.Text = Sht1.Range("E37").Value
End With
' set position marker for the chart object to Cell A1
.Top = Sht1.Range("A1").Top
.Left = Sht1.Range("A1").Left
' resize Chart Object
.Width = 1000
.Height = 1000
With .Chart.SeriesCollection(1)
.ApplyDataLabels ' add data lables
End With
End With
End Sub