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

我正在运行下面的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)上运行得非常好,但在另一台上运行(Excel 2010)。 我无法找出相同的原因。

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

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

在Excel 2010中,自动填充只能以单一方向进行,无论是水平方向还是垂直方向。 因此,如果您希望填充2维范围,则应首先水平填充一行(包括源单元格),然后使用该行作为源将整行向下复制。 下面的代码是这样的。

 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