You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

符合条件时复制数据的Excel VBA macro编写问题求助

客户信息空值自动填充VBA宏

功能说明

  • 自动校验C列customerID(客户ID),识别同一客户的相邻两行数据
  • 针对同一客户的两行记录,自动将A、B、D列的非空值填充到同列的空单元格中
  • 适配导出数据可能出现的上行空/下行空场景,符合每个客户最多2行的规则限制

宏代码

Sub 填充客户空值()
    Dim lastRow As Long
    Dim i As Long
    ' 获取当前工作表C列最后一行行号
    lastRow = Cells(Rows.Count, "C").End(xlUp).Row
    ' 从第2行开始遍历(默认第1行为表头,无表头可修改为i=1)
    For i = 2 To lastRow
        ' 校验当前行与下一行是否为同一客户
        If Cells(i, "C").Value = Cells(i + 1, "C").Value And Cells(i, "C").Value <> "" Then
            ' 填充A列空值
            If Cells(i, "A").Value = "" And Cells(i + 1, "A").Value <> "" Then
                Cells(i, "A").Value = Cells(i + 1, "A").Value
            ElseIf Cells(i + 1, "A").Value = "" And Cells(i, "A").Value <> "" Then
                Cells(i + 1, "A").Value = Cells(i, "A").Value
            End If
            ' 填充B列空值
            If Cells(i, "B").Value = "" And Cells(i + 1, "B").Value <> "" Then
                Cells(i, "B").Value = Cells(i + 1, "B").Value
            ElseIf Cells(i + 1, "B").Value = "" And Cells(i, "B").Value <> "" Then
                Cells(i + 1, "B").Value = Cells(i, "B").Value
            End If
            ' 填充D列空值
            If Cells(i, "D").Value = "" And Cells(i + 1, "D").Value <> "" Then
                Cells(i, "D").Value = Cells(i + 1, "D").Value
            ElseIf Cells(i + 1, "D").Value = "" And Cells(i, "D").Value <> "" Then
                Cells(i + 1, "D").Value = Cells(i, "D").Value
            End If
            ' 跳过下一行,避免重复处理同一组客户
            i = i + 1
        End If
    Next i
    MsgBox "空值填充完成"
End Sub

使用步骤

  • 打开需要处理的Excel文件,按Alt+F11调出VBA编辑器
  • 右键点击左侧项目窗口中的当前工作簿,依次选择「插入」-「模块」
  • 将上述代码复制粘贴到弹出的模块编辑窗口中
  • 按F5直接运行宏,或回到Excel界面按Alt+F8,选择「填充客户空值」宏后点击执行

注意事项

  • 运行宏前请先备份原始数据,避免误操作导致数据丢失
  • 如果你的表格没有表头,将代码中For i = 2 To lastRow的2修改为1即可

内容的提问来源于stack exchange,提问作者user16831316

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:06:03