根据上面的非空白单元格填充空白单元格

时间:2020-06-20 01:05:44

标签: excel vba

我想根据上面的单元格按顺序填充空白单元格。

要填充的列F的间隔不一致。根据上面的商品编号,最多需要填写两行,最多20行。

需要VBA,而不是公式。

此代码将复制非空白上方的项目并将其粘贴。

Sub FillBlanks()
Columns("F:F").Select
Selection.SpecialCells(xlCellTypeBlanks).Select
Selection.FormulaR1C1 = "=R[-1]C" 
End Sub

我需要按顺序自动填充,直到下一个空白为止。

类似的东西:

OA205S061169
OA205S061170
OA205S061171
OA205S061172
OA205S061173
OA205S061174

2 个答案:

答案 0 :(得分:4)

您可以像现在一样选择空白单元格,然后如下遍历每个区域...

Sub FillBlanks()

    Dim lastRow As Long
    Dim dataRange As Range
    Dim currentArea As Range

    lastRow = Cells(Rows.Count, "F").End(xlUp).Row

    On Error Resume Next
    Set dataRange = Range("F1:F" & lastRow).SpecialCells(xlCellTypeBlanks)
    On Error GoTo 0

    If Not dataRange Is Nothing Then
        For Each currentArea In dataRange.Areas
            With currentArea
                With .Offset(-1, 0).Resize(.Rows.Count + 1)
                    .Cells(1).AutoFill Destination:=.Cells, Type:=xlFillDefault
                End With
            End With
        Next currentArea
    End If

End Sub

请注意,它使用列F查找最后使用的行。但是,根据您的数据,您可能需要使用其他一些列来确定最后使用的行。例如,要使用列A,请改用以下内容...

lastRow = Cells(Rows.Count, "A").End(xlUp).Row

答案 1 :(得分:2)

尝试

Sub FillTest()
    Dim rngDB As Range
    Dim vDB, vSplit
    Dim i As Long, x As Long, n As Integer
    Dim s As String

    Set rngDB = Range("f1", Range("f" & Rows.Count).End(xlUp))
    vDB = rngDB

    For i = 1 To UBound(vDB, 1)
        If vDB(i, 1) <> "" Then
            vSplit = Split(vDB(i, 1), "S")
            s = vSplit(0) & "S"
            x = vSplit(1)
            n = 0
        Else
            n = n + 1
            vDB(i, 1) = s & Format(x + n, "000000")
        End If
    Next i
    rngDB = vDB
End Sub