用于系列自动填充的Excel宏

时间:2016-03-09 12:11:26

标签: excel vba macros

我想问一下如何创建宏来自动填充串行/系列(1,2,3等)从第A2行到数据末尾,其中有来自B列的数据?

我使用此代码:

  Sub FillHandle()
  If IsEmpty(ActiveCell.Value) Then Exit Sub
  If ActiveCell.Row = Rows.Count Then Exit Sub
  If ActiveCell.Column > 1 Then
    If Not IsEmpty(ActiveCell.Offset(, -1)) And Not IsEmpty(ActiveCell.Offset(1, -1)) Then
      Range(ActiveCell, ActiveCell.Offset(, -1).End(xlDown).Offset(, 1)).FillDown
      Exit Sub
    End If
  End If
  If ActiveCell.Column < Columns.Count Then
    If Not IsEmpty(ActiveCell.Offset(, 1)) And Not IsEmpty(ActiveCell.Offset(1, 1)) Then
      Range(ActiveCell, ActiveCell.Offset(, 1).End(xlDown).Offset(, -1)).FillDown
      Exit Sub
    End If
  End If
End Sub

然而,它只是自动填充&#34; 1&#34;全力以赴。

以下是我的Excel表的格式。

enter image description here

提前谢谢!

2 个答案:

答案 0 :(得分:1)

没关系,我找到了解决方案,我也会将它分享给需要它的其他人:

Sub FillSerialNumbers()
  With Range("A2:A" & Range("B" & Rows.Count).End(xlUp).Row)
    .Cells(1, 1).Value = 1
    .DataSeries Rowcol:=xlColumns, Type:=xlLinear, Step:=1, Trend:=False
  End With
End Sub

答案 1 :(得分:1)

Range.AutoFill methodRange.DataSeries不同。

Sub FillHandle()
    Dim lr As Long

    'do not know what this is for
    If IsEmpty(ActiveCell.Value) Then Exit Sub
    'do not know what this is for either
    If ActiveCell.Row = Rows.Count Then Exit Sub

    With Worksheets("Sheet2")   '<~~ you should always know what worksheet you are on
        lr = .Cells(Rows.Count, "B").End(xlUp).Row
        .Cells(2, "A") = 1
        .Range(.Cells(2, "A"), .Cells(lr, "A")).DataSeries _
            Rowcol:=xlColumns, Type:=xlLinear, Step:=1
    End With

    'if the series is to be linear but not 1, 2, 3, etc then supply both
    ' the first and last value and let .Series fill in the difference
    With Worksheets("Sheet2")   '<~~ you should always know what worksheet you are on
        lr = .Cells(Rows.Count, "B").End(xlUp).Row
        .Cells(2, "A") = 1
        .Cells(lr, "A") = 99
        .Range(.Cells(2, "A"), .Cells(lr, "A")).DataSeries _
            Rowcol:=xlColumns, Type:=xlLinear, _
            Step:=(.Cells(lr, "A").Value2 - .Cells(2, "A").Value2) / (lr - 2)
    End With


End Sub

第一个例子是严格的 1,2,3 序数。后者是一个相对系列填充,其中第一个和最后一个值已知,但不一定是行之间的行数。