Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

vba - Finding the Last Row and using it in a formula

I am dealing with a sheet of data that has multiple rows ans columns. Each time the macro runs, the number of rows can be different, so I am trying to find the last row for a column.

With the last row, I am trying to do a calculation. For example: if the row I get is 1200, I can do A1200/A2-1. MY code should explicitly paste the formula in an output worksheet and currently (currently I have to put the last row myself).

Question: How can I get the last row and put it in a formula? Should I assign it to a variable and then use the variable in the formula?

Lines of code I am using:

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Like so. Just remove the variable from the quotes.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...