自动填充下一列VBA

我在这里有一些代码可行,但我有一些麻烦让它连续工作多次。 它所做的是用另一个表格中的公式填充第一个空列。

Dim source As Worksheet Dim destination As Worksheet Dim EmptyColumn As Long Dim LastRow As Long Set source = Sheets("vlookup") Set destination = Sheets("COMMIT") LastColumn = destination.Cells(1,destination.Columns.Count).End(xlToLeft).Column LastRow = Worksheets("COMMIT").Range("A:A").Rows.Count If IsEmpty(destination.Range("A2")) = False Then EmptyColumn = LastColumn + 1 destination.Cells(3, EmptyColumn).Formula = "=INDEX(PORT!$S$5:$S$4000,MATCH(COMMIT!$G3,PORT!$G$5:$G$4000,0))" LastRow = ActiveSheet.UsedRange.Rows.Count Range("AL3").AutoFill destination:=Range("AL3:AL" & LastRow) **'This is where I'm having issues'** End If 

我希望它继续把索引公式放到下一个空列中,但是我只知道如何把它放到我设置的范围内,并且当我再次运行这个macros时不会移动到下一列。

任何想法,我怎么能做到这一点?

感谢Scott帮助我解决这个问题!

现在我有另一个问题,已经popup在我的代码。

 Set cellSource = Worksheets("COMMIT").Range(Cells(1, LastColumn).Address) Set cellTarget = Worksheets("COMMIT").Range(Cells(1, LastColumn), Cells(1, EmptyColumn)) If detntn.Range("A2") <> "" Then cellSource.AutoFill destination:=cellTarget, Type:=xlFillDefault End If 

现在我试图从“提交”工作表中复制公式并将其粘贴到第一个空列的第一个单元格中。 出于某种原因,这段代码无法正常工作。 想知道是否有人可以嗅出为什么。 在此先感谢您的帮助!

部分问题是你已经使用了一个保留字的variables。 看看自动填充function,它使用目的地。

然后我们可以使用Cells()而不是Range来引用最后一列。

 Dim source As Worksheet Dim detntn As Worksheet Dim EmptyColumn As Long Dim LastRow As Long Set source = Sheets("vlookup") Set detntn = Sheets("COMMIT") LastColumn = detntn.Cells(1, detntn.Columns.Count).End(xlToLeft).Column LastRow = Worksheets("COMMIT").Range("A:A").Rows.Count If detntn.Range("A2")<>"" Then EmptyColumn = LastColumn + 1 detntn.Cells(3, EmptyColumn).Formula = "=INDEX(PORT!$S$5:$S$4000,MATCH(COMMIT!$G3,PORT!$G$5:$G$4000,0))" LastRow = ActiveSheet.UsedRange.Rows.Count detntn.Cells(3, EmptyColumn).AutoFill destination:=detntn.Range(detntn.Cells(3, EmptyColumn), detntn.Cells(LastRow, EmptyColumn)) End If