I have a code that looks if any cell in Sheet1
has been changed. All the cells are formulas, so that's why I am using Worksheet_Calculate
. If it's changed, it makes sure the user wants to record the old value as a comment.
Dim cache As Variant
Private Sub Workbook_Open()
cache = getSheetValues(Sheet1)
End Sub
Private Function getSheetValues(sheet As Worksheet) As Variant
Dim arr As Variant
Dim cell As Range
' Get last cell in the used range
Set cell = sheet.Cells.SpecialCells(xlCellTypeLastCell)
' Get all values in the range between A1 and that cell
arr = sheet.Cells.Resize(cell.Row, cell.Column)
If IsEmpty(arr) Then ReDim arr(0, 0) ' Default if no data at all
getSheetValues = arr
End Function
Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
Dim current As Variant
Dim previous As Variant
Dim i As Long
Dim j As Long
Dim prevVal As Variant
Dim currVal As Variant
If Sh.CodeName <> Sheet1.CodeName Then Exit Sub
' Get the values of the sheet and from the cache
previous = cache
current = getSheetValues(Sh)
For i = 1 To WorksheetFunction.Max(UBound(previous), UBound(current))
For j = 1 To WorksheetFunction.Max(UBound(previous, 2), UBound(current, 2))
prevVal = ""
currVal = ""
On Error Resume Next ' Ignore errors when out of array bounds
prevVal = previous(i, j)
currVal = current(i, j)
On Error GoTo 0
If prevVal <> currVal Then
' Change detected: call the function that will treat this
CellChanged Sheet1.Cells(i, j), prevVal
End If
Next
Next
' Update cache
cache = current
ext:
End Sub
Private Sub CellChanged(cell As Range, oldValue As Variant)
Dim answer As Integer
' This is the place where you would put your logic
Sheet1.Activate
answer = MsgBox("Changement de casier!"& Chr(10) & "Garder l'historique de "& Chr(10) & """"& oldValue & """?", _
vbQuestion + vbYesNo, "Attention")
If answer = vbYes Then
cell.ClearComments
cell.AddComment.Text Text:=oldValue & Chr(10) & Format(Date, "dd-mm-yyyy")
Else: Exit Sub
End If
End Sub
This works fine. However, I don't want it to be looking at the whole sheet. I want it to be looking at 3 named ranges. Tried changing getSheetValues = Range("Colonne8300")
but it doesn't work.