简体   繁体   中英

Excel Tracking Changes VBA

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

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