VBA 检测 Excel 电子表格中的更改
VBA to detect changes in Excel spreadsheet
我有一个 Excel 电子表格,它充当带有多个输入框的表单(这是我的客户所要求的)。我有 "Clear" 和 "Save" 按钮,后者将数据作为记录推送到 Access 数据库。我已经能够提示使用 msgboxes 以便用户在不先保存的情况下无法清除,并且后续保存受到挑战(因为它们很可能是意外的欺骗)但我无法弄清楚如何提示重新保存应该用户在第一次保存后对表单进行更改(尽管清除表单会重置保存标志)。这甚至可以完成吗(用户窗体不是一个选项)?理想情况下,我需要一个宏来检测特定几个单元格中的任何一个何时对其进行了更改。
将其放入 "ThisWorkbook"
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim result As Boolean
Dim sheetName As String
Dim rangeName As String
'You could alternatively create array variables below if interested in multiple sheets/cells
Dim mySheet As String
Dim myRange As String
'User Defined Input. What sheet and range are you interested in tracking changes for?
mySheet = "Worksheet Name"
myRange = "$C"
'Store what changed
sheetName = Target.Parent.Name
rangeName = Target.Address
If sheetName = mySheet And rangeName = myRange Then
'A change occurred for a range you are interested in
result = True
End If
'Did a change occur in your range of interest?
If result = True Then
'This is where you could prompt to save changes.
MsgBox "Change detected in " & sheetName & "!" & rangeName & "."
End If
End Sub
我有一个 Excel 电子表格,它充当带有多个输入框的表单(这是我的客户所要求的)。我有 "Clear" 和 "Save" 按钮,后者将数据作为记录推送到 Access 数据库。我已经能够提示使用 msgboxes 以便用户在不先保存的情况下无法清除,并且后续保存受到挑战(因为它们很可能是意外的欺骗)但我无法弄清楚如何提示重新保存应该用户在第一次保存后对表单进行更改(尽管清除表单会重置保存标志)。这甚至可以完成吗(用户窗体不是一个选项)?理想情况下,我需要一个宏来检测特定几个单元格中的任何一个何时对其进行了更改。
将其放入 "ThisWorkbook"
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim result As Boolean
Dim sheetName As String
Dim rangeName As String
'You could alternatively create array variables below if interested in multiple sheets/cells
Dim mySheet As String
Dim myRange As String
'User Defined Input. What sheet and range are you interested in tracking changes for?
mySheet = "Worksheet Name"
myRange = "$C"
'Store what changed
sheetName = Target.Parent.Name
rangeName = Target.Address
If sheetName = mySheet And rangeName = myRange Then
'A change occurred for a range you are interested in
result = True
End If
'Did a change occur in your range of interest?
If result = True Then
'This is where you could prompt to save changes.
MsgBox "Change detected in " & sheetName & "!" & rangeName & "."
End If
End Sub