这是我在Excel中的数据,我正在尝试从中创建一个列图
A列中的数据用于列标签,B列中的数据用于列高度。
我需要通过VBA执行此操作,因此我在录制宏时手动创建了图形。我得到了这段代码:
Sub Macro5()
Range("A1:B10").Select
ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
ActiveChart.SetSourceData Source:=Range("Report!$A$1:$B$10")
ActiveChart.FullSeriesCollection(1).Select
ActiveChart.ChartGroups(1).Overlap = 0
ActiveChart.ChartGroups(1).GapWidth = 0
ActiveChart.ChartTitle.Select
ActiveChart.ChartTitle.Text = "Frequency"
Selection.Format.TextFrame2.TextRange.Characters.Text = "Frequency"
With Selection.Format.TextFrame2.TextRange.Characters(1, 9).ParagraphFormat
.TextDirection = msoTextDirectionLeftToRight
.Alignment = msoAlignCenter
End With
With Selection.Format.TextFrame2.TextRange.Characters(1, 9).Font
.BaselineOffset = 0
.Bold = msoFalse
.NameComplexScript = "+mn-cs"
.NameFarEast = "+mn-ea"
.Fill.Visible = msoTrue
.Fill.ForeColor.RGB = RGB(89, 89, 89)
.Fill.Transparency = 0
.Fill.Solid
.Size = 14
.Italic = msoFalse
.Kerning = 12
.Name = "+mn-lt"
.UnderlineStyle = msoNoUnderline
.Spacing = 0
.Strike = msoNoStrike
End With
ActiveChart.ChartArea.Select
End Sub
现在,当我再次运行这个宏时,它并没有给我我记录这个宏时创建的图形。
所以,我的问题是为什么要这样做,我该如何解决?我如何制作一个图表,就像我手工制作的数据一样?
录制宏对我来说根本不起作用,并给出了一个完全不同的图表,如你所见。
总结一下,我手动创建了一个图形并记录了一个宏,但是运行宏并不会创建我之前创建的图形。
答案 0 :(得分:0)
以下是复制图表时需要采取的编程步骤。
您最初必须遵循的步骤与图表向导所采取的步骤不同。从图表向导生成的代码并不总是有帮助的。
步骤:
将此代码放入空模块并运行它:
Option Explicit
Sub CreateGraph()
Dim ws As Worksheet
Dim rngLabels As Range
Dim rngData As Range
Dim shpChart As Shape
Dim cht As Chart
Dim srs As Series
' set a reference to worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
' get ranges for labels and data
Set rngLabels = ws.Range("A1:A10")
Set rngData = ws.Range("B1:B10")
'uncomment if you want to fake up some data for the this
'ws.Cells.Delete
'rngLabels.Value = WorksheetFunction.Transpose(Array(10, 20, 30, 40, 50, 60, 70, 80, 90, 100))
'rngData.Value = WorksheetFunction.Transpose(Array(0, 1, 4, 9, 4, 3, 6, 4, 8, 6))
' create a chart shape, get chart reference and set source data
Set shpChart = ws.Shapes.AddChart2(201, xlColumnClustered)
Set cht = shpChart.Chart
cht.SetSourceData Source:=rngData, PlotBy:=xlColumns
' update the series object with labels
Set srs = cht.SeriesCollection(1)
srs.XValues = rngLabels
' make the graph 'chunky'
cht.ChartGroups(1).GapWidth = 0
' set chart title
cht.ChartTitle.Text = "Frequency"
End Sub