Excel VBA开发需求:将每行C-I列有效值复制至该行C列
需求说明
- 针对每行搜索C列至I列,找到该行内的第一个非空有效值,将其复制到该行的C列位置。
效果对比
- 操作前:每行C-I列中,C列可能为空,有效值分散在后续列
- 操作后:每行C列填充为该行C-I列中的第一个有效值,后续列内容保留
尝试过的错误代码
代码1
Sub FindCelValandFill() Dim rng As Range Dim lastRow As Long Dim cell As Range lastRow = Cells(Rows.Count, "B").End(xlUp).Row Set rng = Range("C2:I2" & lastRow) For Each cell In rng If cell.Value = "" Then cell.Value = cell.Offset(0, 1).Value End If Next cell End Sub
问题:
- 范围写法错误:
Range("C2:I2" & lastRow)应为Range("C2:I" & lastRow) - 逻辑偏差:逐个替换空单元格为右侧值,并非提取第一个有效值填充到C列
代码2
Sub FindCelValandFill() Dim rng As Range Dim lastRow As Long Dim cell As Range lastRow = Cells(Rows.Count, "B").End(xlUp).Row Set rng = Range("C2:I2" & lastRow) For Each cell In rng If cell.Value = "" Then cell.Value = cell.Parent.Evaluate("=CONCAT(" & cell.Resize(1, 50).Address & ")") End If Next cell End Sub
问题:
- 范围写法错误,且用
CONCAT拼接所有值,不符合“提取第一个有效值”的需求
正确的VBA实现方案
Sub FillFirstValidValueToC() Dim lastRow As Long Dim currentRow As Long Dim col As Integer Dim firstValidValue As Variant ' 以B列为基准获取数据最后一行 lastRow = Cells(Rows.Count, "B").End(xlUp).Row ' 遍历每行(从第2行开始,假设第1行是表头) For currentRow = 2 To lastRow firstValidValue = Empty ' 遍历C到I列(对应列号3到9) For col = 3 To 9 ' 判断单元格是否为非空且非纯空白内容 If Not IsEmpty(Cells(currentRow, col).Value) And Trim(Cells(currentRow, col).Value) <> "" Then firstValidValue = Cells(currentRow, col).Value Exit For ' 找到第一个有效值后终止列循环 End If Next col ' 将有效值赋值到当前行C列 If Not IsEmpty(firstValidValue) Then Cells(currentRow, 3).Value = firstValidValue End If Next currentRow End Sub
代码说明
- 精准定位数据范围:通过B列确定最后一行,避免遍历无效行
- 高效查找逻辑:对每行从C到I列依次检查,找到第一个有效值立即停止查找
- 容错处理:若该行C-I列全为空,C列保持原有状态不变
内容的提问来源于stack exchange,提问作者AnsumanM
相关产品推荐
相关产品推荐

