简体   繁体   中英

VBA to detect changes in Excel spreadsheet

I have an Excel spreadsheet that is acting as a form with a number of input boxes (which is as my client has requested). I have "Clear" and "Save" buttons the latter of which pushes the data through as a record to an Access database. I have been able to prompt using msgboxes so that the user can't clear without first saving, and subsequent saves are challenged (as they are most likely accidental dupes) but I am unable to figure out how to prompt for a re-save should the user make changes to the form after the first save (clearing the form resets the save flag, though). Can this even be done (userform is not an option)? Ideally I would need a macro that would detect when any one of a certain few cells has a change made to it.

Place this in "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$3"

'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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM