I have an Excel sheet which has fields to enter data.
Let's say the total fields is 20. Ten of them are locked by default whenever the user opens the workbook. Now, one of the fields is asking the user to enter a password. If the password was "AAA", then five fields (of the ten locked ones) will be unlocked . If the user inputs a password as "BBB", then all the cells of the worksheet will be read-only and locked.
I am focusing on the case when the user inputs "BBB". I tried this code:
if Range("Password").value="BBB" then
cells.select
selection.locked=true
end if
It gives me an error as " Overflow".
If Range("Password").Value = "BBB" Then
ActiveSheet.UsedRange.Locked = True
End If
It gives me an error as " Overflow".
I doubt you should get an overflow error with this code. An overflow may occur if you use something like Cells.Count
in Excel 2007 onwards. CountLarge
was introduced just because Cells.Count
returns an Integer
value which errors out in Excel 2007 because of increased rows/columns. Cells.CountLarge
returns a Long
value.
Now back to your query.
You do not need to SELECT all cells. In fact you should avoid the use of Select
. You may want to see How to avoid using Select in Excel VBA
Also locking all the cells of the worksheet will be ineffective if you do not protect your worksheet. You can change your code to
If Range("Password").Value = "BBB" Then
With ActiveSheet
.Cells.Locked = True
.Protect "Password"
End With
End If
And if you do not want to use Activesheet
then use something like this
Option Explicit
Sub Sample()
Dim ws As Worksheet
'~~> Change this to the relevant sheet
Set ws = Sheet1
With ws
If .Range("Password").Value = "BBB" Then
.Cells.Locked = True
.Protect "Password"
'~~> To unprotect, uncomment the below
'.UnProtect "Password"
End If
End With
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.