我对VBA比较陌生 - 即使我不理解它也倾向于使用有用的东西我很害怕!
我正在尝试为工作表中的每一行数据生成单独的散点图。我可以配置图表等,但是让它读取每一行并正确迭代是超出我的!
这就是我目前所拥有的:
import sympy
当我运行它时,我得到运行时错误424 - 需要对象。我的问题是:
感谢您的帮助!
萨姆
编辑:
感谢您的帮助 - 我想我现在已经正确更新了它(适用于所有标题并创建新图表!)
Private Sub CommandButton1_Click()
ActiveWorkbook.Charts.Add
Dim i As Integer
For i = 2 To WS.Range("A65536").End(xlUp).Row
With ActiveWorkbook.ActiveChart
'Data?
.ChartType = xlXYScatter
.SeriesCollection.NewSeries
.SeriesCollection(1).Name = "Progress"
.SeriesCollection(1).XValues = "=Sheet2!$B$1:$J$1"
.SeriesCollection(1).Values = "=Sheet2!$B$" & i & ":$J$" & i
'Titles
.HasTitle = True
.ChartTitle.Characters.Text = "valuefromcellN2?"
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Timeline"
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Grade"
.Axes(xlCategory).HasMajorGridlines = True
'Formatting
.Axes(xlCategory).HasMinorGridlines = False
.Axes(xlValue).HasMajorGridlines = True
.Axes(xlValue).HasMinorGridlines = False
.HasLegend = False
End With
Next
End Sub
答案 0 :(得分:0)
Q1我是否以大致正确的方式解决这个问题?
是的,你是。你需要解决一些问题。
Q2我错过了什么导致此运行时错误?
您收到该错误是因为您尚未声明ws
对象。我稍后在下面的代码中解释了如何解决它。
Q3如何从valueN2获取value?实际显示值,而不是文本?
要从特定单元格中获取值,您可以说Range("A1").Value
所以在您的情况下它将是Range("N2").Value
很少有其他事情
使用Excel行时,请避免使用Integer
。使用Long
。在Excel 2007之后,行数增加,Integer
可能无法容纳更大的值。
避免使用65536
等硬编码值。有关如何查找最后一行的信息,请参阅This。
<强>代码强>
我已对代码进行了评论,因此您不应该对其进行理解。但如果你这样做,那就干脆问。
这是你正在尝试的(未经测试)?
Private Sub CommandButton1_Click()
Dim ws As Worksheet
Dim i As Long, LRow As Long
Dim chrt As Chart
'~~> This is where we will have the chart
'~~> We declare the object here. Change as applicable
Set ws = ThisWorkbook.Sheets("Sheet2")
With ws
'~~. Find the last row in Col A
LRow = .Range("A" & .Rows.Count).End(xlUp).Row
'~~> Add Chart
Set chrt = .Shapes.AddChart.Chart
With chrt '<~~ Work with chart and set it's parameters
.ChartType = xlXYScatter
.HasTitle = True
.ChartTitle.Characters.Text = ws.Range("N2").Value '<~~ Set the Value here
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Timeline"
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Grade"
.Axes(xlCategory).HasMajorGridlines = True
'Formatting
.Axes(xlCategory).HasMinorGridlines = False
.Axes(xlValue).HasMajorGridlines = True
.Axes(xlValue).HasMinorGridlines = False
.HasLegend = False
n = 1
'~~> Add series and set it
For i = 2 To LRow
.SeriesCollection.NewSeries
.SeriesCollection(n).Name = "Progress"
.SeriesCollection(n).XValues = "=Sheet2!$B$1:$J$1"
.SeriesCollection(n).Values = "=Sheet2!$B$" & i & ":$J$" & i
n = n + 1
Next i
End With
End With
End Sub