使用此特定流程中的VBA自动填充空白单元格

问题描述 投票:1回答:2

[请问我有这个问题,我正在尝试使用vba实现解决方案。

So cell 
A1 has value John
A2-A3 blank
A4 has value Mary
A5-A9 blank
A10 has value Mike
A11-A14 blank
And A15 has value David

我只想自动填充A列中的空白,如下所示:A2-A3空白处将被约翰填充A5-A9会充满玛丽A11-A14和Mike。

所以从技术上讲,我正在自动使用上面的值填充空白单元格

excel excel-vba
2个回答
0
投票

执行此操作的一个版本是:

Sub Autofill1()

Dim ws As Worksheet
Dim lrow As Long
Dim i As Long

Set ws = Worksheets("Sheet1") 'Set your worksheet name
lrow = ws.Cells(Rows.Count, "A").End(xlUp).Row 'Find last row

For i = 1 To lrow 'Loop from 1st row to last row
    If ws.Cells(i, "A").Value = "" Then 'If the cell value is blank then...
        ws.Cells(i, "A").Value = ws.Cells(i - 1, "A").Value '.. copy the value from previous cell above
    End If
Next i

End Sub

另一个版本是:

Sub Autofill2()

Dim ws As Worksheet
Dim FillRange As Range

Set ws = Worksheets("Sheet1") 'Set your worksheet name

On Error GoTo Errhand 'If range already is filled then go to error handler
For Each FillRange In Columns("A:A").SpecialCells(xlCellTypeBlanks) 'Define range in column A
        If FillRange.Cells.Row <= ActiveSheet.UsedRange.Rows.Count Then 'Check if current row is smaller than last row
            FillRange.Cells = ws.Range(FillRange.Address).Offset(-1, 0).Value 'Fill the empty cells with the non empty values
        End If
Next FillRange

Errhand:
If Err.Number = 1004 Then MsgBox ("Column is already filled")
End Sub

0
投票

已经很长时间了,但是如果我没记错的话,以下应该可以工作:

Dim i As Integer, firstcell As Integer, lastcell As Integer
Dim currentValue As String

firstcell = 1
lastcell = 15
currentValue = ""

For i = firstcell To lastcell
    If Cell(i,1).Value = "" Then
        Cell(i,1).Value = currentValue
    Else
        currentValue = Cell(i,1).Value
    End If
Next i

您遍历单元格,如果其中没有内容,则在其中写入最后一个值。如果它们包含数据,则更新currentValue

© www.soinside.com 2019 - 2024. All rights reserved.