Excel跟踪更改VBA

用户表单和很多VBA都有很大的优势。 我有部分locking一个工作表的问题,同时允许VBA跟踪更改。 目前我使用下面的代码跟踪更改 – 此代码是坐在Microsoft Excel对象>> 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 

另一个代码位于文件夹Forms(我创build用户表单从用户获取一些细节),看起来像这样:

 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 

问题是,用户完成Sheet1后部分保护,但我仍然允许用户更改H列和P列中的数据。当我尝试这样做时,我得到运行时错误“1004”您是单元格或图表试图改变是受保护的,因此是只读的。

不要使用表单保护方法,但仍然可以防止用户更改要保护的单元格。

 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