如何自动填充活动单元格的列直到最后一行

问题描述 投票:0回答:1

尝试执行以下代码:

ActiveCell.Offset(1, 0).Select 'Noting but F2





  ActiveCell.FormulaR1C1 = "=LEFT(RC[-1],4)"





' find last row with data in column "A"

lastRow = Cells(Rows.Count, "A").End(xlUp).Row



' copying the formula from "F2" all the way to the last cell

ActiveCell.AutoFill Destination:=Range(ActiveCell.EntireColumn & lastRow), Type:=xlFillDefault

显示类型不匹配时出现错误。

但是当我尝试时:

ActiveCell.AutoFill Destination:=Range("F2:F" & lastRow), Type:=xlFillDefault

它正常工作,但是我不希望在那儿出现F2:F,因为我不知道将来会在哪一列。

excel vba range autofill
1个回答
0
投票

要回答您的问题,您未指定正确的范围。如您所说,可以指定一个简单范围

  1. 使用字符串格式Range("A1:B4"),其中A1B4是范围的两个相对角。

  2. 将两个角用作单元格,例如Range( Cells(1,1), Cells(4,2) ),其中Cells(1,1)A1Cells(4,2)B4

所以你可以写

ActiveCell.AutoFill Destination:=Range(Cells(2, ActiveCell.Column), Cells(lastRow, ActiveCell.Column)), Type:=xlFillDefault

为了达到您的目标,您也可以避免使用自动填充。 FormulaR1C1格式允许您编写具有“相对”单元格偏移量/地址的公式。因此,自动填充后,desiderd列中的所有单元格将具有相同的FormulaR1C1。然后,您可以避免使用自动填充并为整个列手动设置相同的FormulaR1C1。

因此您可以编写一个更简单的代码,例如:

lastRow = Cells(Rows.Count, "A").End(xlUp).Row
Range(Cells(1, ActiveCell.Column), Cells(lastRow, ActiveCell.Column)).FormulaR1C1 = "=LEFT(RC[-1],4)"
© www.soinside.com 2019 - 2024. All rights reserved.