自动填充变量作为范围失败

时间:2016-10-28 02:43:22

标签: vba

这是我第一次使用.Autofill,但我无法弄明白。我环顾四周,我发现并尝试过的所有东西都做不到。我认为这是最接近我做到的,但我可能会弄错。我尝试使用.Autofill来填充列,但我会在每个For之前进行.Autofill循环,因此我无法一次完成所有操作。< / p>

Dim ws As Worksheet
    Set ws = Worksheets(1)
Dim EquationRange As Range
Dim DestinationRange As Range
Dim RowNumber As Long
    RowNumber = 2

Set EquationRange = ws.Cells(RowNumber, 1)
Set DestinationRange = ws.Cells(RowNumber + 1, 1)

EquationRange.AutoFill Destination:=DestinationRange

我从Dim ws As Worksheet开始,只是Set EquationRange = Cells(RowNumber, 1),但当我搜索类似问题的解决方案时,他们都指定了Worksheets(),但这并不起作用。我一直收到错误

  

Range类的自动填充方法失败

当我在中断模式下检查代码时,它会显示DestinationRange = Empty,但是当我使用Debug.Print DestinationRange.Address(False, False)时,它会给出正确的输出。有什么问题?

1 个答案:

答案 0 :(得分:0)

您收到错误bcoz“目的地必须包含来源范围”。请参阅link。所以,你的代码应该是以下内容

Private Sub test()
  Dim ws As Worksheet
  Dim EquationRange As Range
  Dim DestinationRange As Range
  Dim RowNumber As Long

  Set ws = Worksheets(1)
  RowNumber = 2

  With ws
    Set EquationRange = .Range(.Cells(RowNumber, 1))
    Set DestinationRange = .Range(.Cells(RowNumber, 1), .Cells(RowNumber + 1, 1))
  End With

  EquationRange.AutoFill Destination:=DestinationRange

End Sub