【问题标题】:Error 1004 : autofill method of range class failed vba excel 2010错误 1004:范围类的自动填充方法失败 vba excel 2010
【发布时间】:2017-11-18 04:50:52
【问题描述】:

我正在运行下面的 VBA 代码 -

lastColumn = Cells(5, Columns.count).End(xlToLeft).Column
count_dates = Range("H2").Value

Set cellSource = Range(Cells(6, 13).Address)
Set cellTarget = Range(Cells(6, 13), Cells(count_dates + 5, lastColumn))
cellSource.AutoFill Destination:=cellTarget, Type:=xlFillDefault

代码在一台 PC (Excel 2016) 上运行良好,但在另一台 PC (Excel 2010) 上无法运行。我无法弄清楚同样的原因。

单元格 (6,13) 有一个公式,我想水平向右和垂直向下拖动

我得到的错误是 - 错误 1004:范围类的自动填充方法失败

【问题讨论】:

  • 你基本上是在做 Range(Cells(6, 13), Cells(count_dates + 5, lastColumn)) = Range(Cells(6, 13)) 吗?如果是这样,只需重新编写以避免自动填充。
  • Range(Cells(6, 13).Address)Cells(6, 13) 完全相同...您正在做的是计算cells(6,13) 范围的地址,然后您指的是该地址的范围。 .... 有点像 i want to go to the house that is at the address of the house where Richard lives 而不是 i want to go to Richard's house
  • 您应该告诉我们自动填充单元格中有哪些数据,以便我们重现。
  • @Akshat Agrawal LastColumnCount_Dates 的价值是什么
  • 已编辑问题以使其更清晰并消除歧义

标签: vba excel


【解决方案1】:

在 Excel 2010 中,自动填充仅在一个方向上工作,水平或垂直。因此,如果您希望填充二维范围,您应该首先水平填充一行(包括源单元格),然后将该行用作源将整行向下复制。下面的代码就是这样做的。

Sub AutoFillRange()

    Dim lastColumn As Long
    Dim count_Dates As Long
    Dim cellSource As Range, cellTarget As Range

    lastColumn = Cells(5, Columns.Count).End(xlToLeft).Column
    count_Dates = Range("H2").Value

    Set cellSource = ActiveSheet.Cells(6, "M")
    If lastColumn <> cellSource.Column Then
        ' return an unexpected result if lastColumn is smaller than cellSource.Column
        Set cellTarget = cellSource.Resize(1, Abs(lastColumn - cellSource.Column + 1))
        cellSource.AutoFill Destination:=cellTarget, Type:=xlFillDefault
        Set cellSource = cellTarget
    End If
    Set cellTarget = cellSource.Resize(count_Dates, cellSource.Columns.Count)
    cellSource.AutoFill Destination:=cellTarget, Type:=xlFillDefault
End Sub

【讨论】:

    猜你喜欢
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多