宏以填充空白单元格范围

时间:2018-11-12 16:04:55

标签: excel vba excel-vba

假设我具有A1:C3单元格范围,并且我需要使用A4:C4单元格中的值填写该范围内的任何空白单元格,A列中的示例性单元格将填充为A4,B列中的值来自B4,依此类推。

3 个答案:

答案 0 :(得分:2)

RowsColumns都是动态的。假设最后一行是将用于填充空白的单元格。如果假设是正确的,则可以根据需要添加行和列,并且此代码无需任何修改即可工作

  1. 确定范围的最后一行(由Column A确定)
  2. 确定最后一列(由步骤1中的最后一行确定)
  3. 逐行浏览行
  4. 如果空白为空,则使用与最后一行关联的值填充空白

Option Explicit

Sub Test()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1") '<== Update Sheet Name
Dim LRow As Long, LCol As Long, r As Long, c As Long

LRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
LCol = ws.Cells(LRow, ws.Columns.Count).End(xlToLeft).Column

Application.ScreenUpdating = False
    For c = 1 To LCol
        For r = 1 To LRow - 1
            If ws.Cells(r, c) = "" Then
                ws.Cells(r, c).Value = ws.Cells(LRow, c).Value
            End If
        Next r
    Next c
Application.ScreenUpdating = True

End Sub

以下两个示例均来自同一宏。请注意,它对于您的示例(4 Rows x 3 Columns)和其他表大小(如右侧的示例(8 Rows x 7 Columns)一样正常工作

enter image description here

答案 1 :(得分:0)

如果 A1:C3 中的所有单元格都为空,请考虑:

Sub FillInTheBlanks()
    Range("A1:C3").Value = Range("A4:C4").Value
End Sub

如果 A1:C3 中的某些单元格不为空,请使用:

Sub FillInTheBlanks2()
    For i = 1 To 3
        For j = 1 To 3
            If Cells(i, j) = "" Then
                Cells(4, j).Copy Cells(i, j)
            End If
        Next j
    Next i
End Sub

答案 2 :(得分:-1)

您可以尝试此操作。只需将Worksheets(1)更改为所需的工作表,将4更改为所需的行

Dim rng As Range
Dim cel As Range

With ThisWorkbook.Worksheets(1)
    Set rng = .Range("A1:C3")
    For each cel in rng
        If Len(Trim(CStr(cel.Value))) = 0 Then cel.Value = .Cells(4, cel.Column).Value
    Next
End With