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

时间:2017-01-19 10:03:05

标签: excel vba excel-vba

我正在处理一张包含多行和列的数据。每次宏运行时,行数可以不同,所以我试图找到列的最后一行。

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

问题:如何获取最后一行并将其放入公式中?我应该将它分配给变量然后使用公式中的变量吗?

我正在使用的代码行:

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

2 个答案:

答案 0 :(得分:2)

像这样。只需从引号中删除变量即可。

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

答案 1 :(得分:1)

用户定义的功能怎么样?这样,您可以使用=LastRow(ColumnNumber)将其添加到Excel中的等式中。您可以将其保留在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