假设我具有A1:C3单元格范围,并且我需要使用A4:C4单元格中的值填写该范围内的任何空白单元格,A列中的示例性单元格将填充为A4,B列中的值来自B4,依此类推。
答案 0 :(得分:2)
Rows
和Columns
都是动态的。假设最后一行是将用于填充空白的单元格。如果假设是正确的,则可以根据需要添加行和列,并且此代码无需任何修改即可工作
Column A
确定)
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
)一样正常工作
答案 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