Excel VBA锁定列,包含单元格中的特定值

时间:2017-04-05 13:19:36

标签: excel vba locking

我需要锁定列标题中包含特定值的所有列。我试过以下没有成功。我意识到锁定列后我必须锁定工作表。选择列时出错了。

感谢您的帮助。

    Sub MultipleFindLike()
  For Each cell In Worksheets("LockTest").Range("A1", Range("A1").End(xlToRight))
    If cell Like "COM_*" Then
      Debug.Print "Cell value = " & cell
      Debug.Print "Cell Column = " & cell.Column
      Range(cell, Range(cell).End(xlDown)).Select
    End If
  Next
Worksheets("LockTest").Protect Password:="mypass"
Debug.Print "Done ..."

End Sub

1 个答案:

答案 0 :(得分:0)

我的问题是工作表已被锁定,并且单元格锁定语句不起作用。以下是工作原理。不过,我欢迎更优雅的解决方案。

Sub LockSelectedCells(sheetName As String)
  Dim cell As Range
  Dim sheetProtectPassword As String
  sheetProtectPassword = Range("Reports!sheetProtectPassword")
'  Debug.Print "sheetProtectPassword=" & sheetProtectPassword
  Worksheets(sheetName).Unprotect Password:=sheetProtectPassword
  For Each cell In Worksheets(sheetName).Range("A1", Range("A1").End(xlToRight))
    If cell.Value Like "COM_*" Then
'      Debug.Print "Cell value = " & cell
'      Debug.Print "Cell Column = " & cell.Column
'      Debug.Print "A" & cell.Column
      cell.EntireColumn.Locked = False
    End If
  Next
Worksheets(sheetName).Protect Password:=sheetProtectPassword
Debug.Print "Done ..."

End Sub