Excel Visual Basicmacros – 为图表dynamicselect数据?

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

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.txtinput的数据可以是任意长度的,所以这个程序不起作用。 它只是从D3:H3开始。 我希望图表使用从D3到HX的数据,其中X是数据行的结尾。 我将如何做到这一点? 感谢您帮助一个白痴

可能下面的工作:

 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!

对于这些thigs,我喜欢使用= OFFSET()命名的范围。
请参阅http://www.ozgrid.com/Excel/DynamicRanges.htm或谷歌“exceldynamic范围偏移”