使用VBA创建Excel图表而无需手动输入范围

时间:2013-06-04 20:55:59

标签: excel-vba charts range vba excel

我在网上看了一会儿,尝试了不同的东西,没有工作。我有一组数据,长度各不相同,我写了一个宏将所有这些数据放在一张纸上,现在它们都有不同的行数。我试图将所有这些都放到图表上但是在指定范围时我会卡住。所有的帮助将不胜感激,下面是我从录制的宏操作的代码:

Sub charttest()

    Dim r As Range
    Set r = ActiveSheet.Range("A1").CurrentRegion

    Range("D9").Select
    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.SetSourceData Source:=Range("'OBA 1'!$A$1" & "r.Columns.Coun, r.Rows.Coun")
    ActiveChart.ChartType = xlXYScatterSmoothNoMarkers
End Sub

2 个答案:

答案 0 :(得分:0)

尝试更改以下行:

ActiveChart.SetSourceData Source:=Range("'OBA 1'!$A$1" & "r.Columns.Coun, r.Rows.Coun")

进入(假设ActivesheetOBA 1表:

ActiveChart.SetSourceData Source:=r

或(在其他情况下):

ActiveChart.SetSourceData Source:=Range("'OBA 1'!" & r.Address)

答案 1 :(得分:0)

我查看了我的工作并更新了我的代码,因为我不再满足我的需求,我运行了几个部分的代码并使用上面的方法我最终在我的图表功能上出现错误13,我确定错误来自源代码行。任何人都可以告诉我要走的路吗?

Sub t_feuille(f_Work As Worksheet)

Dim num_line As Integer, t_Work As Worksheet
Dim myrange As Range

'instals time column
f_Work.Activate
f_Work.Cells(1, 1) = "Time"
For num_line = 2 To last_line(t_Work)
  f_Work.Cells(num_line, 1) = num_line - 2
Next

'graph set up

  Set myrange = ActiveSheet.Cells(1, 1).CurrentRegion
  Application.CutCopyMode = False
  ActiveChart.ChartWizard _
    Source:=Sheets(f_Work).Range(myrange), _
    Gallery:=xlXYScatterSmoothNoMarkers, Format:=4, PlotBy:=xlColumns, _
    CategoryLabels:=1, SeriesLabels:=1, HasLegend:=1, _
    Title:=f_Work, CategoryTitle:="", _
    ValueTitle:="", ExtraTitle:=""

End Sub

Function last_line(f_Work) As Integer
Dim num_col As Integer, num_line As Integer

  num_line = 0
  For num_col = 1 To ActiveSheet.Cells(1, 10000).End(xlToLeft).Column
    If ActiveSheet.Cells(100000, num_col).End(xlUp).Row > num_line Then
      num_line = ActiveSheet.Cells(100000, num_col).End(xlUp).Row
    End If
Next

  last_line = num_line
End Function