【问题标题】:how to define a range of cells as an object如何将一系列单元格定义为对象
【发布时间】:2014-07-02 08:28:27
【问题描述】:

我有一个代码,我首先选择一组单元格,然后创建一个图表。这些单元格是输入,因此只要有新条目出现,图表就会更新。 部分代码如下。我需要将源范围定义为我之前选择的单元格。知道我该怎么做吗?

    Range(Selection, Selection.End(xlUp)).Select
    Range(Selection, Selection.End(xlUp)).Select
    Range(Selection, Selection.Offset(0, 5)).Select
    Range(Selection, Selection.Offset(1, 0)).Select
    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.ChartType = xlLineMarkers
    ActiveChart.SetSourceData Source:=Range("Blad3!$B$3:$G$75")
    ActiveChart.SeriesCollection(2).Select
    ActiveChart.SeriesCollection(2).ChartType = xlLine

【问题讨论】:

  • ActiveChart.SetSourceData Source:=Selection
  • 现在选择的是图表,然后它没有选择我的范围
  • 您不必选择图表来修改它,这样您选择的单元格就会保持活动状态。另一种方法是创建一个 Range 变量来保存选择,然后使用该变量设置图表源
  • 你的第一个建议没有用,我收到运行时错误'13',类型不匹配。我试图保存范围,但它也没有工作。尝试将变量定义为范围,然后使用 'set variable = range(selection)

标签: excel vba charts range


【解决方案1】:

第一个解决方案:不使用 ActiveChart,而是为新创建的图表使用变量:

Dim c As Chart

Range("whatever").Select
Set c = ActiveSheet.Shapes.AddChart.Chart
c.ChartType = xlLineMarkers
c.SetSourceData Source:=Selection
c.SeriesCollection(2).ChartType = xlLine

或者,在With 的帮助下,不使用任何变量:

Range("whatever").Select
With ActiveSheet.Shapes.AddChart.Chart
    .ChartType = xlLineMarkers
    .SetSourceData Source:=Selection
    .SeriesCollection(2).ChartType = xlLine
    '...
End With

第二种解决方案:您可以将选择保存在变量中:

Dim r As Range

Set r = Range("whatever")
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlLineMarkers
ActiveChart.SetSourceData Source:=r
ActiveChart.SeriesCollection(2).ChartType = xlLine

你当然可以同时使用这两种方法。

【讨论】:

  • 我得到了所有这些想法,但他们都没有工作,令我惊讶的是=/对于第一个我收到错误消息,对于其他人,图表不会随源数据更新
  • @user3796821 我忘记了AddChart 后面的.Chart。我已经更新了我的答案。但是第三个应该可以工作
  • 还是什么都没有。它不识别源范围 =/
  • 在第一个 - source:= selection 不返回第二个的图形 - 同样的问题:不返回第三个的图形 - 当我更改 Set r = Range("whatever")设置 r = Range(Selection, Selection),代码运行(没有错误消息),但图中没有响应,好像关于源的行不存在
  • @user3796821 Set r = Selection 第三次。对于 1 和 2,您的意思是未创建图表但不会产生任何错误?
【解决方案2】:
    Dim lastRow As Long
    With Sheets("blad3")
    lastRow = .Range("E" & Rows.Count).End(xlUp).Row
    Application.ScreenUpdating = False
    Sheets("Blad1").Select
    Range("C11").Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy
    Sheets("Blad3").Select
    Range("A3").Select
    ActiveSheet.Paste
    Range("e3").Select
    ActiveSheet.Paste
    Range("A3").Select

    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.ChartType = xlLineMarkers
    ActiveChart.SetSourceData Source:=Sheets("Blad3").Range("b3:E" & lastRow)
     ActiveChart.SeriesCollection(1).Select
    ActiveChart.SeriesCollection(1).ChartType = xlLine
    ActiveChart.PlotArea.Select

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 2013-03-09
    • 2020-11-05
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 2021-01-22
    相关资源
    最近更新 更多