VBA根据使用最后一个单元格的相邻列自动填充

我想在这里做的是写一个代码,将自动填充列A到最后一行的数据,根据列B,使用列A中的数据的最后一个单元格作为自动填充的范围。 例如列A是“名称”,B是“date”。 B列有6个date,而列A每隔几行有一个不同的“名称”。 这是我到目前为止:

小测()

Dim lastRow As Long lastRow = Range("B" & Rows.Count).End(xlUp).Row Range("A2").AutoFill Destination:=Range("A2:A" & lastRow) 

结束小组

这是我的问题:

我想运行该脚本,并selectA中的最后一个填充的单元格(例如A4),并自动填充到列B中的数据的最后一行。

我的问题是不断select“A2”而不是A中的最后一个单元格(在本例中为“A4”)来自动填充并填充“A2”列的所有列,到正确的距离。

这将find列A中最后占用的单元格,并使用它:

 Sub test() Dim ws As Worksheet Dim lastRow As Long Dim Alastrow As Long Set ws = ActiveSheet lastRow = ws.Range("B" & ws.Rows.Count).End(xlUp).row Alastrow = ws.Range("A" & ws.Rows.Count).End(xlUp).row Range("A" & Alastrow).AutoFill Destination:=Range("A" & Alastrow & ":A" & lastRow) End Sub 
 Sub copyDown() Dim lastRow As Long, i& lastRow = Range("B" & Rows.Count).End(xlUp).Row For i = 1 to 2 Cells(2,i).AutoFill Destination:=Range(Cells(2,i),Cells(lastRow,i)) next i End Sub 

正如@Findwindow所提到的,你不要改变自动填充的单元格。 要做一个简单的循环(循环遍历列A和B),我喜欢使用Cells([row],[column])然后只是循环通过两个。

如果你不希望它是A2或任何其他,那么只要将第一个Cells(2,i)更改为您想要的外观。

另一个简单的实现方法如下

 Sub simple_way() Range("A2:A" & Range("B" & Rows.Count).End(xlUp).Row).Value = Range("A2").Value End Sub