如果没有要自动填充的行,请获取自动填充宏以停止

时间:2013-03-01 14:47:45

标签: excel excel-vba vba

我有一个电子表格,可以通过自动过滤器宏从数据库中提取某些项目,并将它们放入不同的部分。我有进入的公式,并自动填充到每个部分的每一行。我遇到的问题是如果一个部分只有一行我的宏将调试。下面是我的代码,插入公式并自动填充它们。最后一行是自动填充宏和我需要帮助的那一行。有人可以请我提供一个覆盖,说明如果没有线路自动填充,只需继续下一步。我不确定这段代码会怎样。谢谢

'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)

1 个答案:

答案 0 :(得分:2)

我设置了一个LastRow变量,以你已经的方式计算,并测试它是否大于Selection行:

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

顺便说一下,如果你搜索“VBA避免选择语句”,你会得到一些关于为什么这是一个好主意以及如何做的信息。在这种情况下,我将在代码的开头设置一个CellWithFormula变量:

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

......等等。