贷款摊销表折线图

时间:2018-04-12 21:50:22

标签: vba excel-vba excel

我正在尝试创建一个已在vba excel中创建的贷款摊还表的图表。我使用了以下代码:

 Private Sub CommandButton4_Click()

'Create a line chart of the loan amortization table
Dim pChart As Chart
Dim pRange As Range
Dim axisRange As Range

'Set the range to the cells C8:H23
Set pRange = Range(Cells(8, 4), Cells(23, 8))

'Set the x-axis range to the cells C9:C23
Set axisRange = Range(Cells(9, 3), Cells(23, 9))

'Create the chart as a line chart
Set pChart = Charts.Add
pChart.HasLegend = False
pChart.ChartType = xlLine
pChart.SetSourceData pRange
pChart.PlotBy = xlColumns

'Set the x-axis chart to the created address
pChart.SeriesCollection(1).XValues = "=" & axisRange.Address(False, False, xlA1, xlExternal)

'Choose the location of the chart
pChart.Axes(xlCategory).HasMajorGridlines = True
pChart.Location xlLocationAsObject, Sheet1.Name
Sheet1.ChartObjects.Left = 125
Sheet1.ChartObjects.Top = 250
Cells(1, 1).Select

End Sub

但是,创建图表时,会在x轴上添加许多数字。我添加了它的截图。有谁知道如何更改,所以只有年份数字显示在x轴上?而且,如何使线条的名称可见? Line Chart

1 个答案:

答案 0 :(得分:1)

错字:

'Set the x-axis range to the cells C9:C23
Set axisRange = Range(Cells(9, 3), Cells(23, 9))

您确实将轴范围设置为C9:I23。这应该是

Set axisRange = Range(Cells(9, 3), Cells(23, 3))

您确实将轴范围设置为C9:I23。专业提示:如果你知道整个范围的地址,你可以使用它:

Set axisRange = Range("C9:C23")

我已经清理了代码,假设您要使用活动工作表:

Private Sub CommandButton4_Click()

  'Create a line chart of the loan amortization table
  Dim pChart As Chart
  Dim pRange As Range
  Dim axisRange As Range

  'Set the range to the cells C8:H23
  Set pRange = ActiveSheet.Range("C8:H23")

  'Set the x-axis range to the cells C9:C23
  Set axisRange = ActiveSheet.Range("C9:C23")

  'Create the chart as a line chart
  Set pChart = ActiveSheet.Shapes.AddChart
  pChart.HasLegend = False
  pChart.ChartType = xlLine
  pChart.SetSourceData pRange
  pChart.PlotBy = xlColumns

  'Set the x-axis chart to the created address
  pChart.SeriesCollection(1).XValues = axisRange

  'Choose the location of the chart
  pChart.Axes(xlCategory).HasMajorGridlines = True
  pChart.Parent.Left = 125
  pChart.Parent.Top = 250
  ActiveSheet.Cells(1, 1).Select

End Sub