Excel Visual Basic宏 - 为图表动态选择数据?

时间:2011-02-19 00:59:51

标签: excel vba excel-vba charts

所以,这个问题可能相当愚蠢,但我对Excel VBA不太熟悉。这是我生成的宏代码,它从文本文件中导入数据并绘制图形。

Sub getData()
'
' getData Macro
'

'
With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT;C:\data.txt", Destination:=Range("$D$3"))
    .Name = "data_2"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 437
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With
Range("D3:H4").Select
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlXYScatter
ActiveChart.SetSourceData Source:=Range("Sheet1!$D$3:$H$4")
End Sub

基本上,因为从data.txt输入的数据可以是任意长度,所以该程序不起作用;它只是从D3:H3开始。我想图表使用D3到HX的数据,其中X是数据行的结尾。我该怎么做? 感谢您帮助白痴

2 个答案:

答案 0 :(得分:0)

以下情况可能会有效:

Sub getData()
With ...
     ....
End With
LastRowColH = Range("H65536").End(xlUp).Row
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlXYScatter
ActiveChart.SetSourceData Source:=Range("Sheet1!$D$3:$H$" & CStr(LastRowColH))  
End Sub  

HTH!

答案 1 :(得分:0)

对于这些事情,我喜欢使用= OFFSET()来命名范围 请参阅http://www.ozgrid.com/Excel/DynamicRanges.htm或google了解“excel动态范围偏移”