Possible to Lock Range of cells based on another cell's value?

余生颓废 提交于 2019-12-12 19:14:32

问题


I am using a tracker for testing new changes, and when. If a new change is N/A, I don't want to delete it, I want to disable (and turn gray) all the cells that are available to select the date it was completed. But only in that row. I've tried using the following methods but haven't had luck with any:

  1. Conditional Formatting on the sheet
  2. VBA code that executes when a change is made
  3. Data Validation (think this is possible but am unfamiliar with how this really works)

Here is the code I have:

 Private Sub worksheet_change(ByVal Target As Range)

     Dim keycells As Range

     Set keycells = Range("G:G")

     lastcol = CInt(Sheet1.Cells(1,Sheet1.Columns.Count).End(xlToLeft).Column)

     If Not Application.Intersect(keycells, Range(Target.Address)) Is Nothing Then
         r = Range(Target.Address).Row
         MsgBox "There was a change"
         If Range(Target.Address).Value = "N/A" Then
             MsgBox "we got this far"
             Range("H" & r & ":" & Cells(r, lastcol).Address).Locked = True
         End If

     End If

End Sub

Both message boxes show, but the cells don't lock. So I tried unlocking all cells, then protecting the sheet. Then I set something to "N/A" and get the error "Unable to set the Locked property of the Range Class".

Here is an idea of what my data looks like:

Thanks in advance!


回答1:


Well, Community has been insisting (for days) that I look at this question, relentlessly pushing it to the top of my "relevant" queue, probably because it's tagged with my top 4 tags, and it doesn't technically have an Answer.

So, sorry Moacir, I'm swiping your "commented answer":


  1. Leave it protected,

  2. do Worksheet.Unprotect,

  3. run your code (and Worksheet.Protect) after that.


More Info:

  • Microsoft : Worksheet.Protect Method (Excel)

  • Microsoft : Worksheet.Unprotect Method (Excel)

  • S.O. : How to protect cells in Excel but allow these to be modified by VBA script



来源:https://stackoverflow.com/questions/45987196/possible-to-lock-range-of-cells-based-on-another-cells-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!