Excel Tracking Changes VBA - excel

I have quite big excel with user forms and a lot of VBA going on. I have a problem with locking partially one worksheet and in the same time allowing VBA to track changes.
At the moment I track changes using the code below - this code is sitting under Microsoft Excel Objects >> Sheet1:
Option Explicit
Public preValue As Variant
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Count > 1 Then Exit Sub
Target.ClearComments
Target.AddComment.Text Text:="Previous Value was " & preValue & Chr(10) `& "Revised " & Format(Date, "mm-dd-yyyy") & Chr(10) & "By " & Environ`("UserName")
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Count > 1 Then Exit Sub
If Target = "" Then
preValue = "a blank"
Else: preValue = Target.Value
End If
End Sub
And another bit of code is sitting in the folder Forms ( where I created user form to pick up some details from users) and looks like that:
Dim myPassword As String
myPassword = "123"
Set wsUK = Worksheets("Sheet1")
wsUK.Unprotect Password:=myPassword
' here there is a lot of code that throws data into Sheet1
wsUK.Protect Password:=myPassword
The problem is that after the user form finished Sheet1 is partially protected, but I still allow users to change data in column H and P. When I try to do it I get Run-time error '1004' The cell or chart that you are trying to change is protected and therefore read-only.

Don't use the sheet protect method, but still prevent users from changing the cells you want protected.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Count > 1 Then Exit Sub
If Target.Column = 8 Or Target.Column = 16 Then
Target.ClearComments
Target.AddComment.Text Text:="Previous Value was " & preValue & Chr(10) & "Revised " & Format(Date, "mm-dd-yyyy") & Chr(10) & "By " & Environ("UserName")
Else
Application.EnableEvents = False
Application.Undo
Application.EnableEvents = True
End If
End Sub

Related

I have code that logs changes into a new sheet. How can I add code that will take the user to the most current entry in that log sheet to add a note?

I currently have code that logs any changes made into a separate change log sheet. I need to add in code that takes the user to that newest entry in the change log so that they have to put in a note for why they changed it. I was exploring this option of being taken to that entry or having a pop-up text box that appears when a change is made prompting the user to type in a note that will then be saved with that entry in the log.
Here's my working code:
Dim oldValue As String
Dim oldAddress As String
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim sSheetName As String
Data = "Data"
Dim ssSheetName As String
MoreData = "MoreData"
If ActiveSheet.Name <> "LogDetails" Then
Application.EnableEvents = False
Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Value = ActiveSheet.Name & " – " & Target.Address(0, 0)
Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(0, 1).Value = oldValue
Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(0, 2).Value = Target.Value
Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(0, 3).Value = Environ("username")
Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(0, 4).Value = Now
If ActiveSheet.Name = Data Then
Sheets("LogDetails").Hyperlinks.Add Anchor:=Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(0, 5), Address:="", SubAddress:="'" & Data & "'!" & oldAddress, TextToDisplay:=oldAddress
ElseIf ActiveSheet.Name = MoreData Then
Sheets("LogDetails").Hyperlinks.Add Anchor:=Sheets("LogDetails").Range("A" & Rows.Count).End(xlUp).Offset(0, 5), Address:="", SubAddress:="'" & MoreData & "'!" & oldAddress, TextToDisplay:=oldAddress
End If
Sheets("LogDetails").Columns("A:D").AutoFit
Application.EnableEvents = True
End If
End Sub
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
If Target.Count > 1 Then Exit Sub
If Target.Count = 1 Then
oldValue = Target.Value
End If
oldAddress = Target.Address
End Sub
I couldn't resist to do a bit of refactoring:
It's always a good idea to create a seperate sub-routine for a work like this - and then call the routine from the worksheet_change-event.
Furthermore I am first creating an array with the values to log - and then write this array to the log-sheet. Usually this is for performance reasons - which is not the case for this logging.
But as you can see: it is much easier to read and understand the code - as the reader doesn't have to "walk" along the long code line to see what is happening.
By using a variable for the target range it is pretty easy to select it later.
Regarding your basic question:
This code first asks the user for the comment with a input-box. If he/she doesn't give an answer, according cell will be highlighted and user again asked to put in a comment.
Put this into a normal module
Public Sub addLogEntry(rgCellChanged As Range, oldValue As String, oldAddress As String)
Dim wsChanged As Worksheet
Set wsChanged = rgCellChanged.Parent
Dim wsLogData As Worksheet
Set wsLogData = ThisWorkbook.Worksheets("LogDetails")
'we don't need logging on the logsheet
If wsChanged Is wsLogData Then Exit Sub
'Get comment from user
Dim commentChange As String
commentChange = InputBox("Please enter a comment, why you made this change.", "Logging")
Application.EnableEvents = False
'Collect data to log
Dim arrLogData(6) As Variant
arrLogData(0) = wsChanged.Name & " - " & rgCellChanged.Address(0, 0)
arrLogData(1) = oldValue
arrLogData(2) = rgCellChanged.Value
arrLogData(3) = Environ("username")
arrLogData(4) = Now
arrLogData(6) = commentChange '>>> adjust the column in case your comment column is not G
'get cell to enter log data
Dim rgLogData As Range
Set rgLogData = wsLogData.Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
'write data
rgLogData.Resize(, 7).Value = arrLogData
'create hyperlink
wsLogData.Hyperlinks.Add rgLogData.Offset(, 5), Address:="", SubAddress:="'" & wsChanged.Name & "'!" & oldAddress, TextToDisplay:=oldAddress
'>>> optional: activate log sheet and select comment cell
'If user hasn't entered a comment, activate logsheet and cell
If LenB(commentChange) = 0 Then
wsLogData.Activate
MsgBox "Please enter the comment, why you made the change.", vbExclamation, "Logging"
rgLogData.Offset(, 6).Select
End If
Application.EnableEvents = True
End Sub
And this is how your worksheet_change looks like
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
addLogEntry Target, oldValue, oldAddress
End Sub
Another advantage: if a code reader gets to this he/she immediately understands what will happen (a log entry will be added) - it is not necessary to read the whole code to understand it

Excel VBA Errors Depending on How Column is Filtered

I have a handy function that's called from cell C1 that populates the cell with the filters that have been applied to Column C using the filters dropdown: =ShowColumnFilter(C:C)
As soon as the user clicks OK in the dropdown, the cell displays the filter(s).
However, when I apply a filter to that same column using VBA below from a command button or hyperlink, the column is correctly filtered but the Function ShowColumnFilter returns an error.
'Code Snippet:
With ActiveSheet.Range("A:W")
.AutoFilter Field:=3, Criteria1:="Some Criteria Here"
End With
Function ShowColumnFilter(rng as Range)
'Only the relevant code included here. Works fine when filtering through dropdown, but gives error after applying filter through the VBA in Worksheet_FollowHyperlink.
Dim sh As Worksheet
Dim frng As Range
Set sh = rng.Parent
Debug.Print sh.FilterMode
'When filtered from UI dropdown OR after executing VBA Code Snippet from Worksheet_FollowHyperlink returns TRUE
Debug.Print sh.AutoFilter.FilterMode
'When filtered from UI dropdown returns TRUE but after executing VBA from hyperlink or command button creates an error: "Object variable or With block variable not set"
Set frng = sh.AutoFilter.Range 'Errors only after filtering by executing VBA from separate routine
...
End Function
This one has me perplexed because the function ShowColumnFilter is populating a cell and is not invoked directly by another sub. I'm trying to populate C1 with the filtering that has been applied to the column regardless of how the user filtered it. Any help is greatly appreciated.
Full code here:
Function ShowColumnFilter(rng As Range)
On Error GoTo myErr
'> PURPOSE: Show filters used in a specific column _
USAGE: =ShowColumnFilter(C:C)
Dim filt As Filter
Dim sCrit1 As String
Dim sCrit2 As String
Dim sOp As String
Dim lngOp As Long
Dim lngOff As Long
Dim frng As Range
Dim sh As Worksheet
Dim i As Long
Set sh = rng.Parent
If sh.FilterMode = False Then
ShowColumnFilter = "No Active Filter"
Exit Function
End If
'**** Included only for debugging *****
Debug.Print sh.FilterMode
Debug.Print sh.AutoFilter.FilterMode
'**************************************
Set frng = sh.AutoFilter.Range
If Intersect(rng.EntireColumn, frng) Is Nothing Then
ShowColumnFilter = CVErr(xlErrRef)
Else
lngOff = rng.Column - frng.Columns(1).Column + 1
If Not sh.AutoFilter.Filters(lngOff).On Then
ShowColumnFilter = "No Conditions"
Else
Set filt = sh.AutoFilter.Filters(lngOff)
On Error Resume Next
lngOp = filt.Operator
If lngOp = xlFilterValues Then
For i = LBound(filt.Criteria1) To UBound(filt.Criteria1)
sCrit1 = sCrit1 & filt.Criteria1(i) & " or "
Next i
sCrit1 = Left(sCrit1, Len(sCrit1) - 3)
Else
sCrit1 = filt.Criteria1
sCrit2 = filt.Criteria2
If lngOp = xlAnd Then
sOp = " And "
ElseIf lngOp = xlOr Then
sOp = " or "
Else
sOp = ""
End If
End If
ShowColumnFilter = sCrit1 & sOp & sCrit2
End If
End If
myExit:
Exit Function
myErr:
Call ErrorLog(Err.Description, Err.Number, "GlobalCode", "ShowColumnFilter", True)
Resume myExit
End Function
Sub ErrorLog(strErrDescription As String, lngErrNumber As Long, strSheet As String, strSubName As String, bolShowError As Boolean)
On Error GoTo myErr
'> PURPOSE: Record Errors in an Error Log
If bolShowError = True Then _
MsgBox "An error has occured running " & strSubName & " on worksheet " & strSheet & ": " & Err.Number & " - " & Err.Description, vbInformation, "VBA Error"
myExit:
Exit Sub
myErr:
MsgBox "VBA Error - Error Log: " & Err.Number & " - " & Err.Description
Resume myExit
End Sub
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
On Error GoTo myErr
'> PURPOSE: Fires whenever a hyperlink is clicked on Sheet 1
Dim sValue as String
sValue = "Some Useful Criteria"
'> Select the sheet:
Sheets("MySheetName").Select
With ActiveSheet.Range("A:W")
If Len(sValue) > 0 Then _
.AutoFilter Field:=3, Criteria1:=sValue
End With
'> Go to the top row:
ActiveWindow.ScrollRow = 1
myExit:
Exit Sub
myErr:
Call ErrorLog(Err.Description, Err.Number, "Sheet1", "FollowHyperlink", True)
Resume myExit
End Sub
It looks like the problem you're running into is linked to exactly when your ShowColumnFilter function is running. As a UDF, it's executed when the worksheet is recalculated. Applying an AutoFilter kicks off a recalculation. So if you catch the call stack in your Worksheet_FollowHyperlink routine, you can detect that the ShowColumnFilter function is entered immediately following the .AutoFilter Field:=3, Criteria1:=sValue statement. So your function is actually catching the worksheet and the filter in a somewhat unknown state.
I was able to solve this issue by protecting that section of code by disabling events and automatic calculations:
Sub ApplyTestFilter()
'Hyperlink Code Snippet:
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
With ActiveSheet.Range("A:W")
.AutoFilter Field:=2, Criteria1:=">500"
End With
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
End Sub
This forces the automatic calculations to delay until you've completed your filtering. (NOTE: in some cases you might have to explicitly force the worksheet to recalculate, though I didn't encounter that situation in my small test.)

How to check if Excel table cell has been edited by user?

What are options to monitor changes in an Excel table?
Possible solution I can think of is to have a clone copy of the table, say in a hidden worksheet and a formula which compares both sheets.
Is there any other way?
Well, there are multiple ways.
On way would be to subscribe to Worksheet_Change event with such method:
Private Sub Worksheet_Change(ByVal Target As Range)
'some code, which will compare values and store info in a file
End Sub
I suggested also way of logging such event: take user name and what has changed and write this info to a file.
Also, you'd need to do some extra coding to see if this is the change you are interested in, but this is left for you to discover, as it is to broad to describe all the options here :)
I've come up with a code (as an event based code - Worksheet_Change) like this:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim rg As Range
Set rg = Cells
Dim lastrow As Long
Dim username As String
If Intersect(Target, rg) Is Nothing Then Exit Sub
On Error GoTo ExitHere
Application.EnableEvents = False
With SomeOtherSheet
lastrow = .Cells(.Rows.Count, "H").End(xlUp).Row
.Range("H" & lastrow + 1) = Now
.Range("I" & lastrow + 1) = Target.Address
.Range("J" & lastrow + 1) = Environ("Username")
.Range("K" & lastrow + 1) = Application.username
End With
ExitHere:
Application.EnableEvents = True
End Sub
It records any change made by a user in the given Sheet (the one where the code is written). It will show me in another Sheet who, when and where the change was done. The only problem I have with this matter is that the user has to enable macros, otherwise it doesn't work... I don't know how to reasonably solve this issue...
I totally agree with #Michał Turczyn. For security reasons is better to keep records about the changes. You could use:
Option Explicit
Dim OldValue As String
Private Sub Worksheet_Change(ByVal Target As Range)
MsgBox "The old value was " & OldValue & "." & vbNewLine & _
"The new value is " & Target.Value & "." & vbNewLine & _
"Date of change " & Now & "." & vbNewLine & _
"Change by " & Environ$("computername") & "."
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
OldValue = Target.Value
End Sub

Excel VBA Automatic creation/updating a drop-down list from files/images in a folder

I am looking to merge my scripts to work togheter, my drop-down list (ComboBox) script, to my current script that loads pictures/images into the heading of my Excel sheet.
My script for loading the images looks like this (and works):
Private Sub Worksheet_Change(ByVal Target As Range)
Dim myPict As Picture
Dim PictureLoc As String
If Target.Address = Range("A2").Address Then
ActiveSheet.Pictures.Delete
PictureLoc = "K:\Images" & Range("A2").Value & ".png"
With ActiveSheet.PageSetup
.CenterHeaderPicture.Filename = PictureLoc
.CenterHeaderPicture.Height = 25
'.CenterHeaderPicture.Width = 100
.CenterHeader = "&G"
End With
End If
End Sub
My script that updates the ComboBox with the newest pictures from my folder (and this works also):
Private Sub CommandButton1_Click()
Filename = Dir("K:\Images\", vbNormal)
ComboBox1.Clear
Do While Len(Filename) > 0
ComboBox1.AddItem Filename
Filename = Dir()
Loop
End Sub
My problem is getting my first script (loading images into heading) to run with the value/name chosen in the ComboBox. It works perfect for a normal validationg list in Cell A2, but I can't get it to fetch the value in the ComboBox instead of A2. I have tried changing the first part of the script to the following, but it will not fetch the value:
Dim PictureLoc As String
'If Target.Address = Range("A2").Address Then
If Target.Address = ComboBox1.Address Then
ActiveSheet.Pictures.Delete
'PictureLoc = "K:\Images\" & Range("A2").Value & ".jpg"
PictureLoc = "K:\Images\" & ComboBox1.Value '& ".jpg"
With ActiveSheet.PageSetup
.CenterHeaderPicture.Filename = PictureLoc
.CenterHeaderPicture.Height = 25
'.CenterHeaderPicture.Width = 100
.CenterHeader = "&G"
End With
End If
End Sub
Any suggestions?

VBA Last Change Method

I am looking for a function to print in a comment box, who was the users that changed the data from that cell. What I have for now is this:
Private Sub Worksheet_Change(ByVal Target As Range)
If Range("A" & Target.Row).Value = "" Then GoTo EndeSub
If Not Intersect(Range("C:JA"), Target) Is Nothing Then
On Error GoTo EndeSub
Application.EnableEvents = False
Range("B" & Target.Row) = Now
End If
EndeSub:
Application.EnableEvents = True
End Sub
It "triggers" automatically when someone types something in a cell.
And is printing only the last user name that changed the data, but I want to be some kind of a log, to print all the users. Do you think it is possible?
One way is, insert a New Sheet and name it "Log" and place the two headers like this...
On Log Sheet
A1 --> Date/Time
B1 --> User
Now replace your existing code with this...
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.CountLarge > 1 Then Exit Sub
If Range("A" & Target.Row).Value = "" Then GoTo EndeSub
Dim wsLog As Worksheet
If Not Intersect(Range("C:JA"), Target) Is Nothing Then
On Error GoTo EndeSub
Set wsLog = Sheets("Log")
Application.EnableEvents = False
Range("B" & Target.Row) = Now
wsLog.Range("A" & Rows.Count).End(xlUp).Offset(1, 1) = Environ("UserName")
wsLog.Range("A" & Rows.Count).End(xlUp).Offset(1) = Now
End If
EndeSub:
Application.EnableEvents = True
End Sub
So each time any user makes changes in the target range, the time of change and the user name will be listed on Log Sheet.
Edit:
As per the new setup, these column headers should be there on the Log Sheet.
A1 --> Date/Time
B1 --> User
C1 --> Cell
D1 --> Old Value
E1 --> New Value
Then replace the existing code with the following two codes...
Dim oVal
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.CountLarge > 1 Then Exit Sub
If Range("A" & Target.Row).Value = "" Then GoTo EndeSub
Dim wsLog As Worksheet
If Not Intersect(Range("C:JA"), Target) Is Nothing Then
On Error GoTo EndeSub
Set wsLog = Sheets("Log")
Application.EnableEvents = False
Range("B" & Target.Row) = Now
wsLog.Range("A" & Rows.Count).End(xlUp).Offset(1, 1) = Environ("UserName")
wsLog.Range("A" & Rows.Count).End(xlUp).Offset(1, 2) = Target.Address(0, 0)
wsLog.Range("A" & Rows.Count).End(xlUp).Offset(1, 3) = oVal
wsLog.Range("A" & Rows.Count).End(xlUp).Offset(1, 4) = Target.Value
wsLog.Range("A" & Rows.Count).End(xlUp).Offset(1) = Now
End If
EndeSub:
Application.EnableEvents = True
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.CountLarge > 1 Then Exit Sub
If Not Intersect(Range("C:JA"), Target) Is Nothing Then
oVal = Target
End If
End Sub
In a Public Module
Sub LogChange(Target As Range)
Dim cell As Range, vNew As Variant, vOld As Variant
vNew = Target.value
Application.Undo
vOld = Target.value
Target.value = vNew
With getLogWorksheet
With .Range("A" & .Rows.Count).End(xlUp).Offset(1)
' Array("Date/Time", "UserName", "Worksheet", "Address", "Old Value", "New Value")
.Resize(1, 6).value = Array(Now, Environ("UserName"), Target.Parent.Name, Target.Address(False, False), vOld, vNew)
End With
End With
End Sub
Private Function getLogWorksheet() As Workbook
Dim ws As Worksheet
On Error Resume Next
Set ws = ThisWorkbook.Worksheets("Log")
On Error GoTo 0
If ws Is Nothing Then
Set ws = ThisWorkbook.Worksheets.Add
ws.Visible = xlSheetVeryHidden
ws.Name = "Log"
ws.Range("A1").Resize(1, 6).value = Array("Date/Time", "UserName", "Worksheet", "Address", "Old Value", "New Value")
End If
End Function
In a Worksheet Module
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.CountLarge > 1 Then
Application.Undo
MsgBox "Changing more than 1 cell at a time is prohibited", vbCritical, "Action Undone"
ElseIf Not Intersect(Range("C:JA"), Target) Is Nothing Then
LogChange Target
End If
End Sub
Another bit of code to give you some ideas:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
val_before = Target.Value
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Count > 1 Then
MsgBox Target.Count & " cells were changed!"
Exit Sub
End If
If Target.Comment Is Nothing Then
Target.AddComment
existingcomment = ""
Else
existingcomment = Target.Comment.Text & vbLf & vbLf
End If
Target.Comment.Text Text:=Format(Now(), "yyyy-mm-dd") & ":" & vbLf & Environ$("Username") & _
" changed " & Target.Address & " from:" & vbLf & """" & val_before & _
"""" & vbLf & "to:" & vblkf & """" & Target.Value & """"
End Sub
Any time a cell is selected, it stores the cell's existing value in a variable. If the cell is changed, it creates a new comment in the cell (or appends the existing comment if there is one) with the date, username, cell address, and the "before and after" values. This could be super annoying if someone's trying to make a lot of changes, and if there are multiple changes at once, then it will just warn you without creating a comment. I'd suggest you practice on a blank workbook (or a 2nd copy of the one you're working on) in case there are any problems. Be sure to Google any of the properties/methods than you are unfamiliar with, for the sake of learning, and for building a solution to fit your needs!

Resources