【问题标题】:VBA code for plotting graph with given starting point and ending point用于绘制具有给定起点和终点的图形的 VBA 代码
【发布时间】:2021-03-07 10:03:35
【问题描述】:

我想问一下如何创建VBA代码来绘制具有给定起点和终点的聚集柱形图?我使用inputbox 函数让用户声明起点。例如,起点是 1 月 20 日。然后,代码需要从一组数据中找出起点的单元格名称,例如A30。然后用户需要键入结束点以定义需要绘制的数据范围,例如,Feb-21,它位于单元格 A45 处。那么图表的数据范围应该是从A30:A45, B30:B45

我已经尝试了所有可以在网上找到的方法,但都没有奏效。

提前致谢

【问题讨论】:

  • 请告诉我们您尝试了什么,即使它不能满足您的需要。

标签: excel vba graph


【解决方案1】:

请尝试下一个代码:

Sub createChartChooseSt_EndDate()
   Dim cht As Shape, sh As Worksheet, LastRA As Long, rngPlot As Range
   Dim startP, endP, cellStart As Range, cellEnd As Range
   
   Set sh = ActiveSheet 'use here the sheet you need
   
   LastRA = sh.Range("A" & sh.rows.Count).End(xlUp).row
   'use the standard date format according to your regional settings:
   startP = InputBox("Please enter the Starting poind date (Format dd/mm/yyyy)", "Choose starting date", Date)
   If Not IsDate(startP) Then MsgBox "No valid date format entered (start)...": Exit Sub
   
   endP = InputBox("Please enter the Ending poind date (Format dd/mm/yyyy)", "Choose ending date", Date + 10)
   If Not IsDate(endP) Then MsgBox "No valid date format entered (end)...": Exit Sub

   'create the range to be plotted:
   'find cellStart:
   Set cellStart = sh.Range("A1:A" & LastRA).Find(what:=CDate(startP), lookAt:=xlWhole, LookIn:=xlValues, After:=sh.Range("A1"), SearchDirection:=xlNext)
   If cellStart Is Nothing Then MsgBox "No start date found...": Exit Sub

   'find cellEnd:
   Set cellEnd = sh.Range("A1:A" & LastRA).Find(what:=CDate(endP), lookAt:=xlWhole, LookIn:=xlValues, After:=cellStart, SearchDirection:=xlNext)
   If cellEnd Is Nothing Then MsgBox "No end date found...": Exit Sub
   
   Set rngPlot = sh.Range(sh.cells(cellStart.row, 1), sh.cells(cellEnd.row, 2))
   Set cht = sh.Shapes.AddChart
    With cht.Chart
        .HasTitle = True
        .ChartTitle.Text = "My custom chart"
        .SetSourceData Source:=rngPlot
        .ChartType = xl3DBarClustered
    End With
End Sub

请在测试后发送一些反馈。

您可以为创建的图表命名,下次运行代码时,通过一些修改,它可能会检查图表是否存在,并且只更改新选择的日期开始/日期结束的数据源...

【讨论】:

  • @ztee:你没抽时间测试一下上面的代码吗?如果经过测试,它没有满足您的需求吗?
  • 嗨,它没有满足我的需求。因为我发现我需要日期在一行中,并且相应的数据在另一行上。同时,在excel表格里面,有很多重复的日期,导致代码运行失败。
  • @ztee: 我听不懂...上面的代码让您可以根据您的输入分别选择要选择的开始日期和结束日期 rows (s)。当然,如果所选日期存在于活动工作表的 A:A 列中。 “有很多重复的日期”是什么意思?图表范围是根据第一个(开始)日期行和结束日期行构建的。它不以这种方式工作吗?您的日期范围是否已排序?如果没有,这就是你想要的?代码是否返回错误?
  • @ztee:如果再过两天再回答,不说代码问题,那很难得到帮助。 对解决你的问题更感兴趣至少是奇怪的......
猜你喜欢
  • 1970-01-01
  • 2017-12-27
  • 2018-03-20
  • 1970-01-01
  • 2022-07-06
  • 2020-10-15
  • 1970-01-01
  • 2015-03-31
  • 1970-01-01
相关资源
最近更新 更多