帮我写一段excel VBA代码,要求当单元格变更时,发送邮件给相关人员
时间: 2024-05-01 10:18:11 浏览: 119
Excel-VBA宏编程实例源代码-当单元格选取范围被改变时执行代码.zip
好的,我可以帮你编写一个Excel VBA代码以实现此功能。以下是示例代码:
```
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Dim cell As Range
Set rng = Range("A1:Z100") '要监控的单元格范围
If Not Application.Intersect(Target, rng) Is Nothing Then
For Each cell In Intersect(Target, rng)
If cell.Value <> cell.Value2 Then '当值发生变化时
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = "相关人员邮箱地址"
.CC = ""
.Subject = "变更通知"
.Body = "您好,以下单元格发生了变更:" & vbCrLf & _
"单元格:" & cell.Address & vbCrLf & _
"变更前值:" & cell.Value2 & vbCrLf & _
"变更后值:" & cell.Value & vbCrLf & _
"请知晓。"
.Send '直接发送邮件,如果需要预览可以改为.Display
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End If
Next cell
End If
End Sub
```
你只需要将代码中的“相关人员邮箱地址”替换成你需要发送邮件的人员邮箱地址即可。当单元格的值发生变化时,该代码将自动发送一封邮件通知相关人员。
阅读全文