我正在尝试使用带有VBA的流畅线条来编写Scatter Plot。 我正在尝试从工作表中获取数据并使用VBA在同一工作簿不同工作表中创建带有行和没有标记的散点图。
这是我的工作表的部分快照
A栏中247以下和263至455之间的值在B栏中对应-1.75。
x值在A1:A401
y值在B1:B401
此外,我希望我的图表有标题,标有X和Y轴。我无法确定如何使用x值绘制y值而不是excel在图表上绘制两条单独的线。
这是我需要的图表
这是我用过的代码
Set xData = ThisWorkbook.Worksheets(2).Range("A1:A" & LastRow_this)
Set yData = ThisWorkbook.Worksheets(2).Range("B1:B" & LastRow_this)
Set GraphRange = Union(xData, yData)
'Create a chart
Set cht = ThisWorkbook.Worksheets(1).Shapes.AddChart2
'Give chart some data
cht.Chart.SetSourceData Source:=GraphRange
'Determine the chart type
cht.Chart.ChartType = xlXYScatterLines
这就是它在Excel中给我的。
如何获得所需的结果?
如果范围是动态的,我该怎么办?
答案 0 :(得分:2)
使用散点图,您不想使用" GraphRange"对于整个图表。根据数据和月相,Excel将尝试将X和Y数据绘制为单个系列,这不是您想要的。
而是单独编辑或插入每个系列,并设置X和Y值的范围。您还需要xlXYScatterSmoothNoMarkers
作为图表类型。
尝试使用宏录制器选择范围,添加带有平滑线条的散点图。然后检查代码。这将为您提供有关您需要对代码所做更改的宝贵指示。
答案 1 :(得分:2)
您可以尝试这样的事情......
Sub CreateChart()
Dim wsData As Worksheet, wsChart As Worksheet
Dim LastRow As Long
Dim xData As Range, yData As Range, GraphRange As Range
Dim cht As Shape
Application.ScreenUpdating = False
Set wsChart = Sheets(1)
Set wsData = Sheets(2)
LastRow = wsData.Cells(Rows.Count, 1).End(xlUp).Row
Set xData = ThisWorkbook.Worksheets(2).Range("A1:A" & LastRow)
Set yData = ThisWorkbook.Worksheets(2).Range("B1:B" & LastRow)
Set GraphRange = Union(xData, yData)
'Create a chart
Set cht = ThisWorkbook.Worksheets(1).Shapes.AddChart2(, xlXYScatterLinesNoMarkers)
'Give chart some data
cht.Chart.SetSourceData Source:=GraphRange
cht.Chart.FullSeriesCollection(1).Format.Line.Weight = 5
Application.ScreenUpdating = True
End Sub
答案 2 :(得分:0)
我的代码是
Sub setChart()
Dim LastRow_this As Long
Dim Ws As Worksheet, chtWs As Worksheet
Dim xData As Range, yData As Range
Dim Cht As Chart
Set Ws = ThisWorkbook.Worksheets(2)
Set chtWs = ThisWorkbook.Worksheets(1)
With Ws
LastRow_this = .Range("a" & Rows.Count).End(xlUp).Row
Set xData = .Range("A1:A" & LastRow_this)
Set yData = .Range("B1:B" & LastRow_this)
End With
Set Cht = chtWs.Shapes.AddChart.Chart
With Cht
.ChartType = xlXYScatterLinesNoMarkers
.HasLegend = False
.SeriesCollection.NewSeries
With .SeriesCollection(1)
.XValues = xData
.Values = yData
End With
.Axes(xlCategory).MajorUnit = 50
.Axes(xlCategory).HasMajorGridlines = True
.Axes(xlValue).HasMajorGridlines = True
.Axes(xlCategory).MaximumScale = 460
.Axes(xlCategory).MinimumScale = 50
End With
End Sub