2017-04-06 77 views
1

我創建一個折線圖的一些數據如何獲得最後一個單元格指數在Excel

Sub FinalTest() 
    ActiveSheet.Shapes.AddChart2(332, xlLineMarkers).Select 
    ActiveChart.SetSourceData Source:=Range("A2:D352") 
    ActiveChart.FullSeriesCollection(1).Name = "=sheet1!$C$1" 
    ActiveChart.FullSeriesCollection(2).Name = "=sheet1!$D$1" 
    ActiveChart.HasTitle = True 
    ActiveChart.ChartTitle.Text = "TEST" 
    ActiveChart.SetElement (msoElementLegendRight) 
    With ActiveChart.Parent 
     .Height = 325 ' resize 
     .Width = 3000 ' resize 
     .Top = 100 ' reposition 
     .Left = 350 ' reposition 
    End With   
End Sub 

我的最後一個單元格是D352和該指數的不同工作表變化。我怎樣才能改變代碼,使其通過使用最後使用的單元格索引動態地工作?

+0

如果你的數據是在一個連續的塊,你可以使用'currentregion'。 – SJR

回答

2

假設最後指數是由最後不是空單元格列發出的

變化:

ActiveChart.SetSourceData Source:=Range("A2:D352") 

到:

ActiveChart.SetSourceData Source:=Range("A2:D" & Cells(Rows.Count, 1).End(xlUp).Row) 
0

考慮這一點。

Sub FindingLastRow() 

'PURPOSE: Different ways to find the last row number of a range 
'SOURCE: www.TheSpreadsheetGuru.com 

Dim sht As Worksheet 
Dim LastRow As Long 

Set sht = ThisWorkbook.Worksheets("Sheet1") 

'Ctrl + Shift + End 
    LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row 

'Using UsedRange 
    sht.UsedRange 'Refresh UsedRange 
    LastRow = sht.UsedRange.Rows(sht.UsedRange.Rows.Count).Row 

'Using Table Range 
    LastRow = sht.ListObjects("Table1").Range.Rows.Count 

'Using Named Range 
    LastRow = sht.Range("MyNamedRange").Rows.Count 

'Ctrl + Shift + Down (Range should be first cell in data set) 
    LastRow = sht.Range("A1").CurrentRegion.Rows.Count 

End Sub 

https://www.thespreadsheetguru.com/blog/2014/7/7/5-different-ways-to-find-the-last-row-or-last-column-using-vba

相關問題