Excel VBA自动填充列

时间:2017-01-18 15:20:42

标签: excel vba excel-vba excel-2013

在A栏中,我有一个包含5个名字的列表 - 我希望在B栏中创建不同的团队并将其命名为Team_1,Team_2等等

这是我尝试过的语法......

Function AutoFill()
  Dim KCLR As Long
  KCLR = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row
  Range("B2").Select
  ActiveCell.FormulaR1C1 = "Team_1"
  Selection.AutoFill Destination:=Range("B2:" & KCLR)
End Function

然而,在Selection.AutoFill Destination:=Range("B2:" & KCLR)行上我收到错误

  

范围(" B2:"& KCLR)=方法'范围'对象' _Global'失败

如果需要,我需要做什么才能成功AutoFill

2 个答案:

答案 0 :(得分:2)

Selection.AutoFill Destination:=Range("B2:" & KCLR)应为Selection.AutoFill Destination:=Range("B2:B" & KCLR),因为KCLR正在返回一个数字。

答案 1 :(得分:1)

关注@ harun24hr回答,为了更好的编码实践,请避免使用SelectActiveCellSelection,并使用完全限定的Range

见下面的例子:

Function AutoFill()

  Dim KCLR As Long

  KCLR = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row
  Range("B2").FormulaR1C1 = "Team_1"
  Range("B2").AutoFill Destination:=Range("B2:B" & KCLR)

End Function