错误1004:范围类的自动填充方法失败vba excel 2010

时间:2017-11-18 04:50:53

标签: excel vba excel-vba

我正在运行以下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:范围类的自动填充方法失败

1 个答案:

答案 0 :(得分: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