简体   繁体   English

使用动态单元格引用将单元格复制到最后一行

[英]Copy Cell Down to Last Row with Dynamic Cell References

I am using the Find method to identify columns which have been populated with headers. 我正在使用Find方法来标识已填充标题的列。 Then offsetting my selection down one row and entering either a string or a formula. 然后将我的选择向下偏移一行,然后输入字符串或公式。 Then I want to paste my selection down the column to the Last populated row. 然后,我要将我的选择粘贴到该列的最后一个填充行。 It's really just the syntax of the last line of the code I'm looking to repair. 它实际上只是我要修复的代码的最后一行的语法。

Dim i As Integer
Dim g As Integer
i = 0
g = 0
Dim Rtitles(3) As String

Rtitles(0) = "NAME OF M4"
Rtitles(1) = "M4 NUMBER"
Rtitles(2) = "X-Ref ID"
Rtitles(3) = "ADDRESS ID"

Range("A1").Select

Do Until i = 17
    If ActiveCell <> "" Then
        ActiveCell.Offset(0, 1).Activate
        i = i + 1
    Else
        ActiveCell = Rtitles(g)
        g = g + 1
    End If
Loop

'Determines Last Row
Dim LastRow As Long
LastRow = ActiveSheet.Cells(1048575, 3).End(xlUp).Row


'This section Populates the Four newly titled columns
i = 0
Do Until i = 4

Cells.Find(What:=Rtitles(i), After:=ActiveCell, LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False).Activate
ActiveCell.Offset(1, 0).Activate
[...]
If i = 2 Then ActiveCell.FormulaR1C1 = _
    "=IF(ISERROR(FIND(""_"",RC[-1])),RC[-1],LEFT(RC[-1],LEN(RC[-1])-3))"
Range(ActiveCell).AutoFill Destination:=Range(ActiveCell, Cells(LastRow,activecolumn))

It's really just the syntax of the last line of the code I'm looking to repair. 它实际上只是我要修复的代码的最后一行的语法。

There is no need to use AutoFill. 无需使用自动填充。 You can enter a formula in the entire range in one go. 您可以一次输入整个范围内的公式。

Replace 更换

Range(ActiveCell).AutoFill Destination:=Range(ActiveCell, Cells(LastRow,activecolumn))

with

Dim ColName As String

'~~> Gets the Column Letter of active cell
ColName = Split(Cells(, ActiveCell.Column).Address, "$")(1)

Range(ActiveCell.Address & ":" & ColName & lastrow).Formula = _
Range(ActiveCell.Address).Formula

EDIT 编辑

BTW do not use LastRow = ActiveSheet.Cells(1048575, 3).End(xlUp).Row to find the last row. BTW不要使用LastRow = ActiveSheet.Cells(1048575, 3).End(xlUp).Row查找最后一行。 One should never hard code values. 一个永远不要硬编码值。 You may want to see THIS on how to find last row. 你可能想看看如何找到最后一行。

要获取第3列的最后一行(“ C”),请使用:

LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "C").End(xlUp).Row

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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