使用VBA绘制线图不同的工作表

我有7个Excel工作表,其中包含我想用来生成带有标记的线图的数据。 我能够在第一个工作表上创build折线图,但是我无法在第二个工作表上重新创build正确的图表。 我刚刚录制了一个macros,以了解如何在VBA中进行绘图,所以我不确定这是否是生成线图的最佳方法,但实质上第一列A将包含X值,而其他列B将会包含Y数据值。

这里是我的代码片段:

Worksheets("OCM_VMonM24").Shapes.AddChart2(332, xlLineMarkers).Select ActiveChart.SetSourceData Source:=Range("OCM_VMonM24!$A$1:$I$2544") ActiveChart.FullSeriesCollection(1).Delete ActiveChart.FullSeriesCollection(1).XValues = "=OCM_VMonM24!$A$3:$A$2544" ActiveChart.ChartTitle.Select ActiveChart.ChartTitle.Text = "O-CAMS -24V" Selection.Format.TextFrame2.TextRange.Characters.Text = "O-CAMS -24V" ActiveChart.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis) Selection.Format.TextFrame2.TextRange.Characters.Text = "Self_Test_GV" 

这适用于在第一个工作表上正确绘制数据,所以我只是试图复制和粘贴另一个工作表,但它只是绘制第一个Excel工作表中的graphics与第二个工作表中的数据。 这里是复制和粘贴版本:

  Worksheets("OCM_VMonM12").Shapes.AddChart2(332, xlLineMarkers).Select ActiveChart.SetSourceData Source:=Range("OCM_VMonM12!$A$1:$I$2544") ActiveChart.FullSeriesCollection(1).Delete ActiveChart.FullSeriesCollection(1).XValues = "=OCM_VMonM12!$A$3:$A$2544" ActiveChart.ChartTitle.Select ActiveChart.ChartTitle.Text = "O-CAMS -12V" Selection.Format.TextFrame2.TextRange.Characters.Text = "O-CAMS -12V" ActiveChart.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis) Selection.Format.TextFrame2.TextRange.Characters.Text = "Self_Test_GV" 

尝试改变你的代码:

 With Worksheets("OCM_VMonM24").Shapes.AddChart2(332, xlLineMarkers).Chart .SetSourceData Source:=Range("OCM_VMonM24!$A$1:$I$2544") .FullSeriesCollection(1).Delete .FullSeriesCollection(1).XValues = "=OCM_VMonM24!$A$3:$A$2544" With .ChartTitle .Text = "O-CAMS -24V" .Format.TextFrame2.TextRange.Characters.Text = "O-CAMS -24V" End With .SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis) .Axes(xlCategory, xlPrimary).AxisTitle.Text = "Self_Test_GV" End With 

也…你可能只能添加

  Worksheets("OCM_VMonM12").Activate 

在前面

  Worksheets("OCM_VMonM12").Shapes.AddChart2(332, xlLineMarkers).Select 

select一个非活动表中的形状往往导致错误…