Open xlam file in read only mode if USERNAME does not match

abc_xyz

New Member
Joined
Jan 12, 2022
Messages
47
Office Version
  1. 2016
Platform
  1. Windows
I have created an xlam file which is saved on the shared drive and a dozen of people use it now. However, I'm not able to save any update I make to any of my code as it opens the file in read only mode. Is there a way I could check for the USERNAME and if it does not match then open the xlam file in read only mode?
I did test the below code but it does not work.

VBA Code:
Private Sub Workbook_Open()
    OpenInReadOnlyNew
End Sub


Sub OpenInReadOnlyNew()

   ' Replace "TargetUserName" with the username you want to match against
    Dim targetUserName As String
    targetUserName = "ABC123"  'in lower case
   
    ' Get the current username
    Dim currentUserName As String
    currentUserName = Environ("USERNAME")
   
    ' Check if the current user name matches the target user name
    If LCase(currentUserName) <> targetUserName Then
        ActiveWorkbook.ChangeFileAccess Mode:=xlReadOnly
        'MsgBox ("Opened in read only mode")
    End If
   
End Sub
 

Excel Facts

Excel motto
Not everything I do at work revolves around Excel. Only the fun parts.
It would be ThisWorkbook not ActiveWorkbook since an add-in is always hidden.
 
Upvote 0
T
It would be ThisWorkbook not ActiveWorkbook since an add-in is always hidden.
Tired, but does not work. Other users can still edit the add-in and save it. Unfortunately, I get a pop up that file file is opened in read only mode when I try to save it.
 
Upvote 0

Forum statistics

Threads
1,215,072
Messages
6,122,968
Members
449,095
Latest member
Mr Hughes

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top