我在“CPU_STAT”工作表中有下表:
我在同一个工作簿中有一个“CPU_STAT_GRAPH”工作表,我在其中提取了用于生成图形的列。
使用的代码:
Sub test()
Dim sourceColumn1 As Range, targetColumn1 As Range
Dim sourceColumn2 As Range, targetColumn2 As Range
Dim sourceColumn3 As Range, targetColumn3 As Range
Set sourceColumn1 = Workbooks("KPI_stats_v1.xls").Worksheets("CPU_STAT").Columns("D")
Set targetColumn1 = Workbooks("KPI_stats_v1.xls").Worksheets("CPU_STAT_GRAPH").Columns("A")
Set sourceColumn2 = Workbooks("KPI_stats_v1.xls").Worksheets("CPU_STAT").Columns("G")
Set targetColumn2 = Workbooks("KPI_stats_v1.xls").Worksheets("CPU_STAT_GRAPH").Columns("B")
Set sourceColumn3 = Workbooks("KPI_stats_v1.xls").Worksheets("CPU_STAT").Columns("I")
Set targetColumn3 = Workbooks("KPI_stats_v1.xls").Worksheets("CPU_STAT_GRAPH").Columns("C")
sourceColumn1.Copy Destination:=targetColumn1
sourceColumn2.Copy Destination:=targetColumn2
sourceColumn3.Copy Destination:=targetColumn3
Range("A1:C5").Select
ActiveSheet.Shapes.AddChart2(240, xlXYScatterSmooth).Select
ActiveChart.SetSourceData Source:=Range("CPU_STAT_GRAPH!$A$1:$C$5")
ActiveChart.SetElement (msoElementPrimaryValueGridLinesNone)
ActiveChart.SetElement (msoElementPrimaryCategoryGridLinesNone)
ActiveChart.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis)
ActiveChart.SetElement (msoElementPrimaryValueAxisTitleAdjacentToAxis)
ActiveChart.ChartTitle.Select
ActiveChart.ChartTitle.Text = "CPU Utilization"
Selection.Format.TextFrame2.TextRange.Characters.Text = "CPU Utilization"
With Selection.Format.TextFrame2.TextRange.Characters(1, 15).ParagraphFormat
.TextDirection = msoTextDirectionLeftToRight
.Alignment = msoAlignCenter
End With
End Sub
“CPU_STAT_GRAPH”中的输出为:
一切都如预期。我只需要正确地重命名图形的轴。垂直轴为Percent
,水平为Hour
。
如何将其合并到代码中?此外,您可以看到我的代码是一个非常基本的代码,它没有明确定义要从左侧数据使用的X轴和Y轴。如何使用最少的代码行优化我的代码并使其更加智能化:)
[[新手到VBA编码:)]]
答案 0 :(得分:1)
添加轴标题的语法与您在图表标题中添加的语法非常相似。在将来,您可以学习很多东西,并通过记录宏然后手动执行步骤来查看代码的样子 - 但要添加轴,请使用以下语法:
ActiveChart.SetElement (msoElementPrimaryCategoryAxisTitleAdjacentToAxis)
ActiveChart.SetElement (msoElementPrimaryValueAxisTitleAdjacentToAxis)
然后添加您可以使用的标题:
ActiveChart.Axes(xlCategory, xlPrimary).AxisTitle.Text = "Hour"
ActiveChart.Axes(xlValue, xlPrimary).AxisTitle.Text = "Percent"
但我真的建议录制,以便您可以看到所有可以通过的格式和相关参数,这也是一个很好的学习方法。希望这有帮助!
还有一件事,因为所有这些命令都使用ActiveChart,你也可以使用with循环。因此,您可以将所有ActiveChart元素组合在一起,并可以说:
With ActiveChart
.Axes(xlCategory, xlPrimary).AxisTitle.Text = "Hour"
.Axes(xlValue, xlPrimary).AxisTitle.Text = "Percent"
End With