查找最后一行并在公式中使用它

我正在处理一个有多行和多列的数据表。 每次运行macros时,行数都可能不同,所以我正在尝试查找列的最后一行。

最后一行,我试图做一个计算。 例如:如果我得到的行是1200,我可以做A1200 / A2-1。 我的代码应明确地粘贴在输出工作表中的公式(目前我必须把自己的最后一行)。

问题:如何获得最后一行并将其放入公式中? 我应该把它分配给一个variables,然后在公式中使用variables?

我正在使用的代码行:

Sub Output() Dim LastRowA As Long LastRowA = Worksheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Row 'this is my current method, it works using specific cells. 'I would like to change the D1662, for example, for a floating reference that gets the last row Worksheets("Sheet2").Range("C2:C2").Formula = "='TIME SERIES'!D1662/'TIME SERIES'!D2-1" End Sub 

像这样。 只要从引号中删除variables。

 Sub Output() Dim LastRowA As Long LastRowA = Worksheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Row 'this is my current method, it works using specific cells. 'I would like to change the D1662, for example, for a floating reference that gets the last row Worksheets("Sheet2").Range("C2:C2").Formula = "='TIME SERIES'!D" & LastRowA & "/'TIME SERIES'!D2-1" End Sub 

用户定义的函数怎么样? 这样,你可以将它添加到excel中的方程=LastRow(ColumnNumber) 。 你可以在vba编辑器中保留这个值,并在excel中设置单元格值为“ =LastRowValue("SheetName",1)/A2-1 ”,其中1将是A列。

 Function LastRowValue(WorksheetName As String, Col As Long) As Long '======================================================================= 'This can be typed into an excel cell as a normal function '"=LastRow("SheetName",ColumnNumber)" The Column Number is indexed 'starting with A=1 so C=3 and AA=27. Enter the WorksheetName in 'quotes "WorksheetName". '======================================================================== Dim LR As Long 'LR will find the last row in column number "col" in WorksheetName. LR = ThisWorkbook.Sheets(WorksheetName).Cells(Rows.Count, Col).End(xlUp).Row 'LastRowValue will be the output of this function and will be the value of 'the last row in WorksheetName. LastRowValue = Cells(LR, Col).Value End Function