VBA当B列不为空时自动赋值

当B列内容不为空时,自动监测,给K、L列自动赋值,减少输入工作量。

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    ' 仅处理以“月”开头且以“日”结尾的工作表
    If Sh.Name Like "*月*日" Then
        Dim affectedRange As Range
        Set affectedRange = Intersect(Target, Sh.Columns("B"))
        
        If Not affectedRange Is Nothing Then
            Application.EnableEvents = False
            
            Dim cell As Range
            For Each cell In affectedRange
                If Trim(cell.Value) <> "" Then
                    ' B列非空:K列和L列赋值为"无"
                    Sh.Cells(cell.Row, "K").Value = "无"
                    Sh.Cells(cell.Row, "L").Value = "无"
                Else
                    ' B列为空:清除K列和L列内容
                    Sh.Cells(cell.Row, "K").ClearContents
                    Sh.Cells(cell.Row, "L").ClearContents
                End If
            Next cell
            
            Application.EnableEvents = True
        End If
    End If
End Sub

监视以月日格式的工作表。

posted @ 2026-03-20 01:00  孤独的小苗  阅读(6)  评论(0)    收藏  举报