在图表中设置X轴比例

时间:2018-08-28 14:36:30

标签: excel vba excel-vba

我编写了一个程序,用于根据用户输入设置在Excel图表中可见的值范围。当x轴中有日期时,该程序将运行。当我尝试修改具有数字而不是日期的x轴的代码时,它将引发错误。

这是有效的代码(图表的x轴是excel格式的日期):

Sub xaxis_reset()
  Dim start_date As Variant
  Dim end_date As Variant
  Dim w As Long, ws As Long
  Dim z As Long, obj As Long

  start_date = InputBox("Start Date")
  end_date = InputBox("End Date")
  ws = ActiveWorkbook.Worksheets.Count - 2

  For w = 1 To ws
    obj = Worksheets(w).ChartObjects.Count
    For z = 1 To obj
      Worksheets(w).ChartObjects(z).Activate
      With ActiveChart
        .Axes(xlCategory).MinimumScale = DateValue(start_date)
        .Axes(xlCategory).MaximumScale = DateValue(end_date)
      End With
    Next z
  Next w
End Sub

这是我尝试修改代码以使其在x轴上具有数字(年-月)的图表中起作用的方法。

Sub xaxis_reset()
  Dim start_yr_mnth_cd As Variant
  Dim end_yr_mnth_cd As Variant
  Dim w As Long, ws As Long
  Dim z As Long, obj As Long

  start_yr_mnth_cd = InputBox("Start YR_MNTH_CD")
  end_yr_mnth_cd = InputBox("End YR_MNTH_CD")
  ws = ActiveWorkbook.Worksheets.Count - 2

  For w = 1 To ws
    obj = Worksheets(w).ChartObjects.Count
    For z = 1 To obj
      Worksheets(w).ChartObjects(z).Activate
      With ActiveChart
        .Axes(xlCategory).MinimumScale = start_yr_mnth_cd
        .Axes(xlCategory).MaximumScale = end_yr_mnth_cd
      End With
    Next z
  Next w
End Sub

.Axes(xlCategory).MinimumScale = start_yr_mnth_cd行引发错误。

我尝试将start_yr_mnth_cdend_yr_mnth_cdVariant更改为Long。我还尝试将图表中的x轴值更改为常规格式,而不是数字。我对excel文件中的源数据进行了类似的更改,尽管我认为这不会有所作为。我不确定在这一点上还有什么地方。

只要有帮助,这就是x轴源数据的样子:

201701
201702
201703
201704
201705
201706
201707
201708
201709
201710
201711
201712
201801
201802
201803
201804
201805
201806
201807

1 个答案:

答案 0 :(得分:1)

尝试使用下面的代码(复制所有内容)。我添加的私有函数基本上采用YYYYMM格式,并将其转换为Excel可以理解的日期格式。

Sub xaxis_reset()
  Dim start_yr_mnth_cd As Variant
  Dim end_yr_mnth_cd As Variant
  Dim w As Long, ws As Long
  Dim z As Long, obj As Long

  start_yr_mnth_cd = InputBox("Start YR_MNTH_CD")
  end_yr_mnth_cd = InputBox("End YR_MNTH_CD")

  start_yr_mnth_cd=ConvertYYYYMM_To_Date(start_yr_mnth_cd)
  end_yr_mnth_cd=ConvertYYYYMM_To_Date(end_yr_mnth_cd)
  ws = ActiveWorkbook.Worksheets.Count - 2

  For w = 1 To ws
    obj = Worksheets(w).ChartObjects.Count
    For z = 1 To obj
      Worksheets(w).ChartObjects(z).Activate
      With ActiveChart
        .Axes(xlCategory).MinimumScale = start_yr_mnth_cd
        .Axes(xlCategory).MaximumScale = end_yr_mnth_cd
      End With
    Next z
  Next w
End Sub

Private Function ConvertYYYYMM_To_Date(vDate As Variant) As Date

ConvertYYYYMM_To_Date = DateValue(Right(vDate, 2) & "-" & Left(vDate, 4))

End Function

希望这会有所帮助