2014-02-14 162 views
1

我對於使用VBA非常新,特別是在Excel上格式化圖表,但已經遇到問題。我正在嘗試生成一個圖形,但參考單元的行將根據可用數據而變化。VBA函數動態調整圖表數據範圍

現在,我的數據在AE741:AG762範圍內,但在下一次迭代中,行可能不同。你能幫我寫一個代碼,根據我的數據動態調整圖表數據範圍嗎?我手邊有行參考(即每次迭代我知道我的數據開始和結束,在本例中爲741到762)。我還有另一個單元格報告的範圍地址,因此在我的情況下,單元格Y10的值爲AE741:AG762。

我想我需要的唯一東西(但沒有設法做)是將這個範圍值調用到我的VBA函數中。

Chart_Test Macro 
Set myRange = Workbook().Worksheet(3).Cell(25, 10).Value 
ActiveSheet.Shapes.AddChart.Select 
ActiveChart.ChartType = xlLine 
ActiveChart.SetSourceData Source:=Range("AE741:AG762") 
ActiveChart.SeriesCollection(2).Select 
ActiveChart.SeriesCollection(2).AxisGroup = 2 
ActiveChart.SeriesCollection(2).Select 
ActiveChart.Legend.Select 
Selection.Delete 
ActiveChart.Axes(xlCategory).Select 
ActiveChart.SeriesCollection(2).Select 
ActiveChart.SeriesCollection(2).ChartType = xlColumnClustered 
ActiveChart.SeriesCollection(2).Select 
With Selection.Format.Fill 
    .Visible = msoTrue 
    .ForeColor.ObjectThemeColor = msoThemeColorAccent6 
    .ForeColor.TintAndShade = 0 
    .ForeColor.Brightness = -0.25 
    .Transparency = 0 
    .Solid 
End With 
ActiveChart.SeriesCollection(1).Select 
With Selection.Format.Line 
    .Visible = msoTrue 
    .ForeColor.RGB = RGB(0, 176, 240) 
    .Transparency = 0 
End With 
End Sub 

非常感謝您的幫助! 本傑明

回答

0

更改這些行:

Set myRange = Workbook().Worksheet(3).Cell(25, 10) 
ActiveChart.SetSourceData Source:=Range("AE741:AG762") 

爲了這些的:

Dim myRange As Range 'myRange must be declared as Range 
'Ensure that "ThisWorkbook" is alright for you, meaning that you are running this code 
'from the Workbook containing the value you want at cell(25,10) 
Set myRange = ThisWorkbook.Worksheets(3).Cell(25, 10) '.Cell(25, 10) Or .Range("Y10") 
ActiveChart.SetSourceData Source:=Range(myRange.Address) 
'Or simply 
ActiveChart.SetSourceData Source:=myRange