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

请求编写Excel宏:满足条件时自动插入数据并跳过已占用行

Excel宏实现方案

一、M1-M3下拉列表配置步骤

  • 选中单元格M1,点击数据选项卡 → 数据验证
  • 在对话框中,允许类型选择「序列」,来源输入=OFFSET($B$1,0,0,COUNTA($B:$B),1),点击确定(自动抓取B列所有非空值作为下拉选项)
  • 重复上述操作,为M2设置来源=OFFSET($C$1,0,0,COUNTA($C:$C),1),为M3设置来源=OFFSET($D$1,0,0,COUNTA($D:$D),1)

二、VBA宏代码

按Alt+F11打开VBA编辑器,插入模块后粘贴以下代码:

Sub FillH_I_J()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim criteria1 As String, criteria2 As String, criteria3 As String
    Dim fillText As String
    Dim fillCount As Integer, filledRows As Integer
    Dim i As Long
    
    ' 指定当前工作表
    Set ws = ActiveSheet
    
    ' 读取配置参数
    criteria1 = ws.Range("M1").Value
    criteria2 = ws.Range("M2").Value
    criteria3 = ws.Range("M3").Value
    fillText = ws.Range("M4").Value
    fillCount = ws.Range("M5").Value
    
    ' 参数合法性校验
    If criteria1 = "" Or criteria2 = "" Or criteria3 = "" Then
        MsgBox "请先选择M1-M3的条件!", vbExclamation
        Exit Sub
    End If
    If fillText = "" Then
        MsgBox "请在M4输入要插入的文本!", vbExclamation
        Exit Sub
    End If
    If fillCount <= 0 Or Not IsNumeric(fillCount) Then
        MsgBox "M5请输入正整数!", vbExclamation
        Exit Sub
    End If
    
    ' 获取数据区域最后一行
    lastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
    filledRows = 0
    
    ' 遍历数据行(假设第1行为表头)
    For i = 2 To lastRow
        ' 匹配条件且H/I/J均为空(判定为未占用行)
        If ws.Cells(i, "B").Value = criteria1 And _
           ws.Cells(i, "C").Value = criteria2 And _
           ws.Cells(i, "D").Value = criteria3 And _
           ws.Cells(i, "H").Value = "" And _
           ws.Cells(i, "I").Value = "" And _
           ws.Cells(i, "J").Value = "" Then
            
            ' 填充目标列数据
            ws.Cells(i, "H").Value = fillText
            ws.Cells(i, "I").Value = Date
            ws.Cells(i, "J").Value = Time
            filledRows = filledRows + 1
            
            ' 达到指定填充行数则终止循环
            If filledRows = fillCount Then
                Exit For
            End If
        End If
    Next i
    
    ' 结果反馈与异常提示
    If filledRows = 0 Then
        MsgBox "未找到符合条件的空行,请检查条件或表格数据!", vbInformation
    ElseIf filledRows < fillCount Then
        MsgBox "仅找到" & filledRows & "个符合条件的空行,已完成填充!", vbInformation
    Else
        MsgBox "已成功填充" & filledRows & "行数据!", vbInformation
    End If
End Sub

三、核心逻辑说明

  • 参数校验:提前拦截未配置条件、空文本、无效数字等异常输入
  • 行占用判定:仅处理B/C/D列匹配M1-M3条件,且H/I/J列均为空的行
  • 填充规则:H列写入M4文本,I列写入系统当日日期,J列写入当前时间
  • 终止机制:填充行数达到M5指定数量,或遍历完所有数据行后停止
  • 异常提示:无符合条件的空行时,直接弹窗告知用户

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:40:24