如何获取Excel中的最后一个单元格索引

我正在创build一些数据的折线图

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,这个索引因不同的纸张而异。 我怎样才能改变代码,以便它通过采取最后使用的单元格索引dynamic地工作?

假设最后一个索引是由列A中最后一个不为空的单元格给出的

更改:

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

至:

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

考虑一下。

 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