【问题标题】:Code works in Module but not in worksheets Error 1004代码在模块中有效,但在工作表中无效 错误 1004
【发布时间】:2018-01-26 15:58:18
【问题描述】:

希望在下面的这段代码中获得帮助。它适用于模块 1,但不适用于任何工作表。我用我有限的知识尽了最大的努力,但无法解决它。

Sub lastrow()
    Dim MCFPSheet As Worksheet
    Set MCFPSheet = ThisWorkbook.Worksheets("MCFP Referrals YTD")

    Dim lastrow As Long
    lastrow = MCFPSheet.Range("I2").End(xlDown).Row

    With MCFPSheet.Range("R8")
        .AutoFill Destination:=Range("R8:R" & lastrow&)
    End With

    With MCFPSheet.Range("S2")
        .AutoFill Destination:=Range("S2:S" & lastrow&)
    End With

    With MCFPSheet.Range("T2")
        .AutoFill Destination:=Range("T2:T" & lastrow&)
    End With

    With MCFPSheet.Range("U2")
        .AutoFill Destination:=Range("U2:U" & lastrow&)
    End With

    With MCFPSheet.Range("V2")
        .AutoFill Destination:=Range("V2:V" & lastrow&)
    End With

    With MCFPSheet.Range("W2")
        .AutoFill Destination:=Range("W2:W" & lastrow&)
    End With
End Sub

我收到了

错误 1004

.AutoFill Destination:=Range("R8:R" & lastrow&) 行中。

【问题讨论】:

  • 因为您的自动填充目标缺少工作表参考。因此,将“Destination:=”替换为 Destination:=MCFPSSheet。
  • 啊,非常感谢!

标签: excel runtime-error autofill vba


【解决方案1】:

根据@Sixthsense 的评论,您需要为您的目的地指定工作表,如果它们都是单行的,那么所有这些With 语句也没有多大意义。

这样使用With会更短:

Sub lastrow()
    Dim MCFPSheet As Worksheet
    Set MCFPSheet = ThisWorkbook.Worksheets("MCFP Referrals YTD")

    Dim lastrow As Long
    lastrow = MCFPSheet.Range("I2").End(xlDown).Row

    With MCFPSheet
        .Range("R8").AutoFill Destination:=.Range("R8:R" & lastrow)
        .Range("S2").AutoFill Destination:=.Range("S2:S" & lastrow)
        .Range("T2").AutoFill Destination:=.Range("T2:T" & lastrow)
        .Range("U2").AutoFill Destination:=.Range("U2:U" & lastrow)
        .Range("V2").AutoFill Destination:=.Range("V2:V" & lastrow)
        .Range("W2").AutoFill Destination:=.Range("W2:W" & lastrow)
    End With
End Sub

请注意,Destination:=.Range 现在还通过在 Range 之前使用前导 . 来引用 MCFPSheet 表!
我还从lastrow& 中删除了&,我认为其中没有任何意义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 2013-01-16
    • 2011-12-17
    相关资源
    最近更新 更多