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
Related
I have some formulas set via vba to change the value in columns H, J, K, L and N. Those changes are based on G column value and a Submit button, this works fine.
When I do the process to lock them to avoid the user from editing, that says to unlock the whole sheet then lock the ones I need, after this I modify the G column and get:
"Autofit Method of Range Class Failed".
I use it on H column.
This get highlighted:
Sheet1.Range("H11:H50").Rows.EntireRow.AutoFit
You are trying to change protected cells using VBA while the protection is on. You can work around this various ways, however, the most simple solution is something like the following:
Sub Example()
Sheet1.Unprotect "YOURPASSWORD" 'if no password was used, you don't need to include it
Sheet1.Range("H11:H50").Rows.EntireRow.AutoFit
Sheet1.Protect "YOURPASSWORD"
End Sub
Alternative solution:
By using this in the on open procedure of your workbook. VBA can make changes on locked cells, but users can not.
One Caveat: if an error occurs in the code, this will reset and you need to close and reopen the worksheet in order for this to function again
Private Sub Workbook_Open()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
ws.Protect UserInterfaceOnly:=True
Next ws
End Sub
How to allow different users (John, Paul and Mika) to edit different cells in worksheet ?
John is to edit only cells A2 to C5 (RANGE 1)
Mika is to edit only cells E2 to G5 (RANGE 2)
Paul is to edit only cells H2 to K5 (RANGE 3)
In 'allow users to edit ranges', I created 3 ranges for above cells with no password. Each range contains the user name permission.
When I select range 1, then the allow users to edit ranges option is disabled.
I'm not able to do apply same for other 2 users...
Can someone please help and provide the right steps / vba code?
In the workbook_beforeclose event we lock all cells. In the workbook.open event we obtain the user's logon name and selectively unlock the desired range for that logon.
If the user doesn't enable macros then everything is protected, if they do enable then only the desired range is available. (You must close the spreadsheet yourself once for the protection to take effect). This assumes a corporate environment in which logging on is enforced. This code goes into the workbook module:
Option Explicit
Const pword = "your password here"
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim ws As Worksheet
For Each ws In Worksheets
ws.Unprotect pword
ws.UsedRange.Locked = True
ws.Protect pword
Next ws
End Sub
Private Sub Workbook_Open()
Dim LogonName As String
LogonName = Environ("UserName")
Dim rangetoedit As Range
Select Case LogonName
Case "John"
Set rangetoedit = Worksheets(1).Range("A2:C5")
Case "Paul"
Set rangetoedit = Worksheets(1).Range("H2:K5")
Case "Mika"
Set rangetoedit = Worksheets(1).Range("E2:G5")
End Select
Worksheets(1).Unprotect pword
rangetoedit.Locked = False
Worksheets(1).Protect pword
End Sub
You will want to password protect your vba code as well
I've created a table for data entering. However, as user use it, they insert rows in the middle of the table. That messes the formula up as the functions were designed only work forward. Also sometimes when the user add row manually (just by typing into the next row after the last row of the table), the function were filled automatically but the function is incorrect quite often.
So I added a button to add the rows to the table and that works without problems. Now I want to disable the ability for user to add rows manually, meaning rows can ONLY be added via clicking the button.
As far as I research, people all suggesting using protect sheet functionality. But it would remove all ability to add rows including via VBA. Other offer the VBA that only prevent inserting rows via right click at the Rows Column. I need to disable all user-accessible ways.
This is the code for the button (if it's of any relevant).
Sub InsertRow_Click()
Dim i As Integer
For i = 1 To 10
ActiveSheet.ListObjects("Invoice").ListRows.Add alwaysinsert:=True
Next i
End Sub
When using sheet protection, you could add Userinterfaceonly= true, this will prevent user interference, but VBA code will still work.
Private Sub Workbook_Open()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
ws.Protect Password:="secret", UserInterFaceOnly:=True
Next ws
End Sub
or if you want to protect just one sheet:
Private Sub Workbook_Open()
Worksheets("YourSheetName").Protect Password:="secret", UserInterFaceOnly:=True End Sub
Or just take protection off before running your macro and put it on afterwards:
Sub InsertRow_Click()
ActiveSheet.Unprotect Password:="secret"
Dim i As Integer
For i = 1 To 10
ActiveSheet.ListObjects("Invoice").ListRows.Add alwaysinsert:=True
Next i
ActiveSheet.protect Password:="secret"
End Sub
Userinterfaceonly and tables looks if it's no good match
My goal is to protect sheets with password.
So when user open the workbook I want that all sheets except one will be hidden( Very hidden). When user enter the password all sheets will be visible. How can I hide and show lot of sheets using vba code, is there any simple techniques? I mean is it possible to hide "Tab selection facility"?
Before, let me point out how Excel files are not secure:
Your code will be part of the file's XML, so inspecting the underlying data, anyone who wants to can find out how to get your password.
Now that you've been warned, here the code that you must include at the workbook open event. It will hide everything (to prevent scenarios where the sheets would have been left visible upon closing the book), then ask a password.
Public Sub UnlockSheets()
' 1 - hide every sheet, except the desired one
Dim aWorksheet As Worksheet
For Each aWorksheet In ActiveWorkbook.Worksheets
If aWorksheet.Name <> "desired sheet name" Then
aWorksheet.Visible = xlVeryHidden
Next
' 2 - ask for the password
Dim userPassword As String
userPassword = InputBox("Please enter your password")
If userPassword = "my_password" Then
RevealSheets
Else
MsgBox "Wrong password!", vbCritical
Application.DisplayAlerts = False
ActiveWorkbook.Close False
End If
End Sub
Public Sub RevealSheets()
'3 - Hide all the sheets
Dim aWorksheet As Worksheet
For Each aWorksheet In ActiveWorkbook.Worksheets
aWorksheet.Visible = xlSheetVisible
Next
End Sub
Another problem here is that the user can stop all macros by holding the SHIFT key (if I recall right). Needless to say... it's not too secure. Then again, Excel files aren't known for incredible safety.
With a trigger like a check box I want to protect my work book. I tried Excel 2003:
thisworkbook.protect("password",true,true)
thisworkbook.unprotect("password")
It's not working. Any suggestions?
I agree with #Richard Morgan ... what you are doing should be working, so more information may be needed.
Microsoft has some suggestions on options to protect your Excel 2003 worksheets.
Here is a little more info ...
From help files (Protect Method):
expression.Protect(Password, Structure, Windows)
expression Required. An expression that returns a Workbook object.
Password Optional Variant. A string that specifies a case-sensitive password for the worksheet or workbook. If this argument is omitted, you can unprotect the worksheet or workbook without using a password. Otherwise, you must specify the password to unprotect the worksheet or workbook. If you forget the password, you cannot unprotect the worksheet or workbook. It's a good idea to keep a list of your passwords and their corresponding document names in a safe place.
Structure Optional Variant. True to protect the structure of the workbook (the relative position of the sheets). The default value is False.
Windows Optional Variant. True to protect the workbook windows. If this argument is omitted, the windows aren’t protected.
ActiveWorkbook.Protect Password:="password", Structure:=True, Windows:=True
If you want to work at the worksheet level, I used something similar years ago when I needed to protect/unprotect:
Sub ProtectSheet()
ActiveSheet.Protect "password", True, True
End Sub
Sub UnProtectSheet()
ActiveSheet.Unprotect "password"
End Sub
Sub protectAll()
Dim myCount
Dim i
myCount = Application.Sheets.Count
Sheets(1).Select
For i = 1 To myCount
ActiveSheet.Protect "password", true, true
If i = myCount Then
End
End If
ActiveSheet.Next.Select
Next i
End Sub
in your sample code you must remove the brackets, because it's not a functional assignment; also for documentary reasons I would suggest you use the := notation (see code sample below)
Application.Thisworkbook refers to the book containing the VBA code, not necessarily the book containing the data, so be cautious.
Express the sheet you're working on as a sheet object and pass it, together with a logical variable to the following sub:
Sub SetProtectionMode(MySheet As Worksheet, ProtectionMode As Boolean)
If ProtectionMode Then
MySheet.Protect DrawingObjects:=True, Contents:=True, _
AllowSorting:=True, AllowFiltering:=True
Else
MySheet.Unprotect
End If
End Sub
Within the .Protect method you can define what you want to allow/disallow. This code block will switch protection on/off - without password in this example, you can add it as a parameter or hardcoded within the Sub. Anyway somewhere the PW will be hardcoded. If you don't want this, just call the Protection Dialog window and let the user decide what to do:
Application.Dialogs(xlDialogProtectDocument).Show
Hope that helps
Good luck - MikeD
To lock whole workbook from opening, Thisworkbook.password option can be used in VBA.
If you want to Protect Worksheets, then you have to first Lock the cells with option Thisworkbook.sheets.cells.locked = True and then use the option Thisworkbook.sheets.protect password:="pwd".
Primarily search for these keywords: Thisworkbook.password or Thisworkbook.Sheets.Cells.Locked