如果没有要自动填充的行,请自动填充macros停止

我有一个电子表格,通过自动筛选macros从数据库中提取某些项目,并将其放入不同的部分。 我有公式进入,并自动填充到每一节的每一行。 我遇到的问题是如果一节只有一行我的macros将debugging。 下面是我的代码插入公式和自动填充它们。 最后一行是自动填充macros和我需要帮助的一个。 有人可以请给我一个覆盖,说如果没有线路自动填充,只是继续下一步。 我不知道这个代码将如何去。 谢谢

'To insert formulas ActiveCell.Offset(0, 1).Select ActiveCell.FormulaR1C1 = "=IF(RC5<'Data Entry'!R2C2,""*"","""")" ActiveCell.Offset(0, 1).Select ActiveCell.FormulaR1C1 = "=IF(RC18=TRUE,IFERROR(VLOOKUP(RC2,Database!C[-2]:C[9],11,FALSE),""""),0)" ActiveCell.Offset(0, 1).Select ActiveCell.FormulaR1C1 = "=IFERROR(VLOOKUP(RC2,Database!C[-3]:C[8],10,FALSE),"""")" ActiveCell.Offset(0, 1).Select ActiveCell.FormulaR1C1 = "=IFERROR((VLOOKUP(RC9,Pull!C1:C5,4,FALSE))*RC4,"""")" ActiveCell.Offset(0, 1).Select ActiveCell.FormulaR1C1 = "=IFERROR((VLOOKUP(RC9,Pull!C1:C5,5,FALSE))*RC4,"""")" ActiveCell.Offset(0, 1).Select ActiveCell.FormulaR1C1 = "=IFERROR(SUM(RC4,RC6:RC7),"""")" ActiveCell.Offset(0, 1).Select ActiveCell.FormulaR1C1 = "=IFERROR(VLOOKUP(RC2,Database!C[-7]:C[4],6,FALSE),"""")" ActiveCell.Offset(0, 1).Select ActiveCell.FormulaR1C1 = "=IF(RC18=TRUE,IFERROR(VLOOKUP(RC9,'Pull'!C1:C5,2,FALSE),""""),"""")" ActiveCell.Offset(0, 1).Select ActiveCell.FormulaR1C1 = "=IFERROR(RC8*RC10,"""")" ActiveCell.Offset(0, 1).Select ActiveCell.FormulaR1C1 = "=IFERROR(RC8+RC11,"""")" ActiveCell.Offset(0, 1).Select ActiveCell.FormulaR1C1 = "=IFERROR(RC16*R9C13,"""")" ActiveCell.Offset(0, 1).Select ActiveCell.FormulaR1C1 = "=IF(RC18=TRUE,IFERROR(VLOOKUP(RC9,'Pull'!C1:C5,3,FALSE),""""),"""")" ActiveCell.Offset(0, 1).Select ActiveCell.FormulaR1C1 = "=IFERROR(RC16*RC14,"""")" ActiveCell.Offset(0, 1).Select ActiveCell.FormulaR1C1 = "=IFERROR(RC12/(1-R9C13-RC14),"""")" Range(Cells(Selection.Row, 3), Cells(Selection.Row, 17)).AutoFill Destination:=Range(Cells(Selection.Row, 3), "Q" & Range("B" & Rows.Count).End(xlUp).Row) 

我将设置一个LastRowvariables,计算您已经做的方式,并testing它是否大于select行:

 Dim LastRow as Long LastRow = ActiveSheet.Range("B" & Rows.Count).End(xlUp).Row ... If LastRow > Selection.Row Then Range(Cells(Selection.Row, 3), Cells(Selection.Row, 17)).AutoFill Destination:=Range(Cells(Selection.Row, 3), "Q" & LastRow) EndIf 

顺便说一句,如果你search“VBA避免Select语句”,你会得到一些信息,为什么这是一个好主意,以及如何做到这一点。 在这种情况下,我会在代码的开头设置一个CellWithFormulavariables:

 Dim CellWithFormula as Excel.Range Set CellWithFormula = Activcell CellWithFormula.FormulaR1C1 = "=IF(RC5<'Data Entry'!R2C2,""*"","""")" Set CellWithFormula = CellWithFormula.Offset(0, 1) 

… 等等。