VBA从左到右拖动公式

时间:2013-04-30 13:01:33

标签: excel vba excel-vba

我正在尝试将公式从单元格拖到右侧的另一个单元格(即cellA1 [formula: A2 + A3] -> cellB1 [formula: B2+B3])。这就是我所拥有的:

Dim lastColumn As Long
lastColumn = Workbook2.Worksheets(7).Cells(1, Columns.Count).End(xlToLeft).Column

cellSource = Workbook2.Worksheets(7).Cells(3, lastColumn)
cellTarget = Workbook2.Worksheets(7).Cells(3, lastColumn + 1)

cellSource.AutoFill Destination:=cellTarget, Type:=xlFillDefault

错误是“需要对象”

2 个答案:

答案 0 :(得分:3)

尝试以下代码:

Dim lastColumn As Long, cellSource As Range, cellTarget As Range
lastColumn = Workbook2.Worksheets(7).Cells(1, Columns.Count).End(xlToLeft).Column

Set cellSource = Workbook2.Worksheets(7).Range(Cells(3, lastColumn).Address)
Set cellTarget = Workbook2.Worksheets(7).Range(Cells(3, lastColumn), Cells(3, lastColumn + 1))

cellSource.AutoFill Destination:=cellTarget, Type:=xlFillDefault

答案 1 :(得分:1)

范围是对象,因此在为这些变量赋值时应使用 set 关键字:

试试这个:

Dim lastColumn As Long
lastColumn = Workbook2.Worksheets(7).Cells(1, Columns.Count).End(xlToLeft).Column

set cellSource = Workbook2.Worksheets(7).Cells(3, lastColumn)
set cellTarget = Workbook2.Worksheets(7).Cells(3, lastColumn + 1)

cellSource.AutoFill Destination:=cellTarget, Type:=xlFillDefault