简体   繁体   中英

Copy Formula to last cell in active row range then copy all the way to last column - VBA

I am trying to copy a formula from C2 down to the last cell in the active row range (columns A and B count) then copy that same formula to every column in the active column range (row 1 count)

IE copy formula all the way down then all the way across....

Can you dim both last row and last column in the same Subroutine?

If so, how do I do this? I tried with two subroutines and failed miserably.

Sub ImportSub2()
Dim LastRowColumnA As Long
LastRowColumnA = Cells(Rows.Count, 1).End(xlUp).Row
Range("C2:C" & LastRowColumnA).Formula = "=$A2&C$1"

Call ImportSub3
End Sub

Sub ImportSub3()
Dim lastcolumn As Long
lastcolumn = Cells(Columns.Count, 1).End(xlUp).Column
Range("C2:C" & lastcolumn).Formula = "=$A2&C$1"
End Sub

Yes, this can be done; your first problem above is that you are not finding the last column correctly.

VBA formulas, especially with a mix of relative and absolute references, work better with R1C1 format. This code directly writes the required formula into the cells of interest:

Sub InjectFormula()
Dim LastRow As Long, LastCol As Long
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
LastCol = Cells(1, Columns.Count).End(xlToLeft).Column
Range(Range("C2"), Cells(LastRow, LastCol)).FormulaR1C1 = "=RC1&R1C"
End Sub

If you want to copy a pre-existing formula from C2, you can instead use

Range(Range("C2"), Cells(LastRow, LastCol)).FormulaR1C1 = Range("C2").FormulaR1C1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM