我有7个Excel工作表,其中包含我想用来生成带标记的折线图的数据。我能够在第一个工作表上创建折线图但是我无法在第二个工作表上重新创建正确的图形。我刚刚录制了一个宏来了解如何在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工作表中使用第二个工作表中的数据绘制图形。这是复制和粘贴版本:
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"
答案 0 :(得分:1)
尝试稍微更改一下代码:
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
选择非活动工作表中的形状通常会导致错误...