这里有一些不使用数组但速度非常快的 VBA。它使用公式,然后将它们粘贴为值。 50,000大约需要一秒钟:
Sub FillColumn()
Dim ws As Excel.Worksheet
Dim FillRange As Excel.Range
Dim FirstValue As Double
Dim ValueIncrement As Double
Dim FirstCell As Long
Dim LastCell As Long
Application.ScreenUpdating = False
Set ws = ActiveSheet
With ws
FirstCell = .Range("A1")
LastCell = .Range("B1")
FirstValue = .Range("A2")
ValueIncrement = .Range("B2")
End With
Set FillRange = ws.Range("D" & FirstCell).Resize((LastCell - FirstCell) + 1, 1)
With FillRange
.Cells(1) = FirstValue
.Offset(1, 0).Resize(.Rows.Count - 1, 1).Formula = "=R[-1]C+" & ValueIncrement
.Value = .Value
.NumberFormat = "hh:mm:ss"
End With
Application.ScreenUpdating = True
End Sub
编辑:解释这一行.Offset(1, 0).Resize(.Rows.Count - 1, 1).Formula = "=R[-1]C+" & ValueIncrement
Offset(1,0) 指的是比 FillRange 低 1 行的范围,例如D2:D50001
.Resize(.Rows.Count - 1, 1) 取前一个并将其缩短一行,例如 D2:D50000
.Formula = "=R[-1]C+" & ValueIncrement 将公式应用于该范围。该公式只是说将 ValueIncrement 添加到上面的单元格中。如果我在这一行之后停止代码,公式看起来像=D1+0.0000578703703703704。通过遵循此most excellent tip by Dick Kusleika,我得到了代码中使用的 R1C1 样式公式。
这是一个数组版本。 50,000似乎更快一些。但是,由于Application.Transpose 的限制,它只适用于65536 个元素。我不确定是否有更好的方法来填充数组,即不使用循环:
Sub FillColumn2()
Dim ws As Excel.Worksheet
Dim FillRange As Excel.Range
Dim FirstValue As Double
Dim ValueIncrement As Double
Dim FirstCell As Long
Dim LastCell As Long
Dim arr As Variant
Dim i As Long
Application.ScreenUpdating = False
Set ws = ActiveSheet
With ws
FirstCell = .Range("A1")
LastCell = .Range("B1")
FirstValue = .Range("A2")
ValueIncrement = .Range("B2")
End With
ReDim arr(FirstCell To LastCell)
arr(1) = FirstValue
For i = FirstCell + 1 To LastCell
arr(i) = arr(i - 1) + ValueIncrement
Next i
Set FillRange = ws.Range("D" & FirstCell).Resize((LastCell - FirstCell) + 1, 1)
FillRange = Application.Transpose(arr)
Application.ScreenUpdating = True
End Sub