VBA实现当B列内容不为空时自动赋值K、L列
同事要求在工作台帐中增加当B列内容不为空时,自动为K列和L列赋值为“无”,Excel只能启用宏功能才能实现。
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
' 仅处理以“3月”开头且以“日”结尾的工作表
If Sh.Name Like "3月*日" 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
运行效果:
输入内容到B列 → K列和L列自动填入“无”
删除B列内容 → K列和L列自动清空
批量操作(如复制粘贴多个单元格) → 循环处理每个单元格,分别判断
这样实现了双向的自动联动,符合实际使用场景。

浙公网安备 33010602011771号