宏/ VBA:数据集具有不同的大小,如何确保宏仅在包含数据的单元格上运行?

时间:2017-11-28 13:14:41

标签: excel vba excel-vba

我在工作表中创建了一个包含1200行的宏。这个数字每周都会改变。本周,我有970行。当我运行内置了一些IF函数的宏时,它为~230行的差异给了我“FALSE”(当我记录宏时,我在列上做了“填充”。

这不重复,因为我找不到任何文章告诉我哪里将代码放在VBA中。

如何确保它仅适用于数据填充的单元格?

我检查了这些资源:

Fill down a row on VBA

Error in finding last used cell in VBA

我认为lastUsedRow可能是我最好的选择,但我不知道将它放在VBA中的位置,或者它是否是我最好的选择。

以下是自动填充的代码段:

Range("J2").Select
ActiveCell.FormulaR1C1 = _
    "=IF(RC[2]=""Marketing CG2"",""Call Group 2"",IF(RC[2]=""Marketing CG3"",""Call Group 3"",IF(RC[2]=""Marketing CG1"",""Call Group 1"",IF(RC[2]=""Marketing"",""EDIT SKILL""))))"
Range("I2").Select
ActiveCell.FormulaR1C1 = _
"=IF(ISNUMBER(SEARCH(""Nurture"",RC[-1])),""New Producer Nurture""," & _
"IF(ISNUMBER(SEARCH(""WB FU"",RC[-1])),""Event Follow Up""," & _
"IF(ISNUMBER(SEARCH(""WS FU"",RC[-1])),""Event Follow Up""," & _
"IF(ISNUMBER(SEARCH(""WS REM"",RC[-1])),""Event Promotion""," & _
"IF(ISNUMBER(SEARCH(""Marketing OB"",RC[-1])),""General Marketing""," & _
"IF(ISNUMBER(SEARCH(""Marketing Direct to Agent"",RC[-1])),""Marketing""," & _
"IF(ISNUMBER(SEARCH(""Info Email Response"",RC[-1])),""Lead Outreach""," & _
"IF(ISNUMBER(SEARCH(""Marketing IB"",RC[-1])),""General Marketing""," & _
"IF(ISNUMBER(SEARCH(""ZProgramsMatch"",RC[-1])),""Lead Outreach""," & _
"IF(ISNUMBER(SEARCH(""Registration Support"",RC[-1])),""General Marketing""," & _
"IF(ISNUMBER(SEARCH(""Complete Market Lead"",RC[-1])),""Lead Outreach""," & _
"IF(ISNUMBER(SEARCH(""Canada"",RC[-1])),""General Marketing""," & _
"IF(ISNUMBER(SEARCH(""Web Contact Form Outreach"",RC[-1])),""Lead Outreach""," & _
"IF(ISNUMBER(SEARCH(""General Product Inquiry"",RC[-1])),""General Marketing""))))))))))))))"
Range("I2").Select
Selection.AutoFill Destination:=Range("I2:I1070")
Range("I2:I1070").Select
Range("J2").Select
Selection.AutoFill Destination:=Range("J2:J1070")
Range("J2:J1070").Select
Columns("I:I").EntireColumn.AutoFit
Columns("J:J").EntireColumn.AutoFit
Columns("J:J").EntireColumn.AutoFit

1 个答案:

答案 0 :(得分:1)

dim lrow as integer放在代码的开头 如果公式结束,请使用此方法

lrow = Range("I" & Rows.Count).End(xlUp).Row

Range("I2").Select
Selection.AutoFill Destination:=Range("I2:I" & lrow)
lrow = Range("J" & Rows.Count).End(xlUp).Row
Range("J2").Select
Selection.AutoFill Destination:=Range("J2:J" & lrow)