[英]Get value of cell on click and store as variable in worksheet_selectionChange sub and then pass variable to worksheet_Change sub?
[英]Private Sub Worksheet_SelectionChange/Worksheet_Change
美好的一天,我需要在一个工作簿中创建 2 个私有宏 - 一个在单击它后存储单元格的内容,第二个将存储单元格的新值并发送和电子邮件与单元格中的旧文本和新文本的正文细胞。
说实话,我不确定这是否是正确的方法(或者甚至可能),但我不经常使用私有宏,所以我将不胜感激。 非常感谢!
这就是我到目前为止所得到的:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Cells.Count > 1 Then Exit Sub
OldCellValue = ActiveCell.text
old_value = OldCellValue
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Area As Range
Dim OutlApp As Object
Dim IsCreated As Boolean
Dim cell As String
Dim old_value As String
Dim new_value As String
Set Area = Range("A1:E20")
If Target.Cells.Count > 1 Then Exit Sub
If Not Intersect(Target, Area) Is Nothing Then
cell = ActiveCell.Address
new_value = ActiveCell.text
On Error Resume Next
Set OutlApp = GetObject(, "Outlook.Application")
If Err Then
Set OutlApp = CreateObject("Outlook.Application")
IsCreated = True
End If
OutlApp.Visible = True
On Error GoTo 0
With OutlApp.CreateItem(0)
.Subject = "Change in table"
.to = "someones email"
.HTMLBody = "Change in cell " & "<B>" & cell & "</B><br>" _
& "Old value: " & old_value & "New value: " & new_value
On Error Resume Next
.Send
Application.Visible = True
On Error GoTo 0
End With
If IsCreated Then OutlApp.Quit
Set OutlApp = Nothing
End With
End If
End Sub
不是重新编写所有代码,但本质上您必须这样做才能在选择单元格时存储值,然后在更改后存储值。 您不需要 newcellvalue 变量,因为 Target 会捕获它。
Dim OldCellValue
Private Sub Worksheet_Change(ByVal Target As Range)
Dim newcellvalue
newcellvalue = Target.Value
MsgBox "Old " & OldCellValue & ", New " & newcellvalue
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
OldCellValue = Target.Value
End Sub
我认为你在正确的轨道上。 我将使用全局变量来跟踪当前/旧值,以便您可以在 Worksheet_Change 事件中进行比较。
像这样的东西:
Private old_value As String
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Cells.Count > 1 Then Exit Sub
old_value = Target.Text
'Debug to check the old_value
'Debug.Print "old_value = " + old_value
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Area As Range
Dim OutlApp As Object
Dim IsCreated As Boolean
Dim cell As String
Dim new_value As String
Set Area = Range("A1:E20")
If Target.Cells.Count > 1 Then Exit Sub
If Not Intersect(Target, Area) Is Nothing Then
new_value = Target.Text
'Debug to compare values
'Debug.Print "new_value = " + new_value
'Debug.Print "old_value = " + old_value
If new_value <> old_value Then
'Debug to compare
'Debug.Print "new_value and old_value are different"
End If
End If
End Sub
请记住,每次在单元格之间导航时都会触发 Worksheet_SelectionChange 事件。 因此,如果您更改单元格的值并按 Enter 键,则 old_value 的值将会更改,因为您正在重置 Worksheet_SelectionChange 事件中的值。 您需要在选择更改之前执行比较并发送电子邮件。
此外,您可能希望对单元格使用 .Value 而不是 .Text。 请参阅这篇文章了解差异: What is the difference between .text, .value, and .value2?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.