我对用户表单和很多VBA都有很大的优势。我有一个问题,部分锁定一个工作表,同时允许VBA跟踪更改。 目前我使用下面的代码跟踪更改 - 此代码位于Microsoft Excel对象>>下工作表Sheet:
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(我创建用户表单以从用户那里获取一些细节),看起来像这样:
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&#39 ;您尝试更改的单元格或图表受到保护,因此是只读的。
答案 0 :(得分:-1)
不要使用表格保护方法,但仍然阻止用户更改您想要保护的单元格。
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