我对 Excel 编码还很陌生,所以我有点困扰。但是,我想尝试锁定特定列,这些列只能由各自的用户解锁。它有效,但是当我尝试使其始终解锁特定行和列时,它会解锁所有单元格。我不知道为什么......我对其进行了编码,以便首先锁定所有单元格,这是我遇到问题的代码:
ws.Cells.Locked = True
Debug.Print "All cells locked"
' Prompt for global password to unlock Rows 1-7 and Columns A-C
globalPassword = InputBox("Please enter the global password:", "Global Password Required")
If globalPassword = "GO123" Then ' Replace with the actual global password
' Unlock Rows 1-7 and Columns A-C
ws.Rows("1:7").Locked = False ' Unlock Rows 1 to 7
ws.Range("A1:C50").Locked = False ' Unlock Columns A-C in the specified range
MsgBox "Rows 1-7 and Columns A-C are now unlocked.", vbInformation
Debug.Print "Rows 1-7 and Columns A-C unlocked"
Else
MsgBox "Incorrect global password. Access denied.", vbExclamation
Exit Sub ' Stop further execution if global password is wrong
End If
我尝试使其与用户输入各自列的密码后解锁某些列的方式相同。而且,虽然它不起作用,但因为我认为 A1:C50 是问题所在,因为它会不断给出以下错误:
错误:无法设置 Range 类的 Locked 属性
所以我只是将其更改为 A1:A50 来先测试一下,并认为它有效,但我想不会,因为它实际上会解锁所有单元......
这应该可以解决你的问题
Sub LockAndUnlockCells()
Dim ws As Worksheet
Dim globalPassword As String
' Set the worksheet you are working on
Set ws = ThisWorkbook.Sheets("Sheet1") ' Change Sheet1 to your sheet name
' Lock all cells
ws.Cells.Locked = True
Debug.Print "All cells locked"
' Prompt for global password to unlock Rows 1-7 and Columns A-C
globalPassword = InputBox("Please enter the global password:", "Global Password Required")
If globalPassword = "GO123" Then ' Replace with the actual global password
' Unlock Rows 1-7 and Columns A-C
ws.Rows("1:7").Locked = False ' Unlock Rows 1 to 7
ws.Range("A1:C50").Locked = False ' Unlock Columns A-C in the specified range
MsgBox "Rows 1-7 and Columns A-C are now unlocked.", vbInformation
Debug.Print "Rows 1-7 and Columns A-C unlocked"
Else
MsgBox "Incorrect global password. Access denied.", vbExclamation
Exit Sub ' Stop further execution if global password is wrong
End If
' Protect the worksheet to enforce lock settings
ws.Protect Password:="yourSheetPassword" ' Replace with the desired sheet password
Debug.Print "Worksheet protected"
End Sub