简体   繁体   中英

How to , remove all other users from shared Workbook , Excel VBA?

I have workbook that is shared (Office 2016) , I use below code to { Remove all other users from this shared Workbook } , it works, But remove only one user per run time and I have to run this code many times to remove all users (except me). should I repeat lines of code to work as supposed or modify it .

Note: although the code has if statement , in case I put End If it gives error !!

Sub Remove_Other_Users_from_Shared_Workbook()

    Dim UsrList()

    UsrList = ThisWorkbook.UserStatus

    For i = 1 To UBound(UsrList, 1)
        If Not (UsrList(i, 1) = Application.UserName) Then ThisWorkbook.RemoveUser (i)
    Next
    
End Sub

It is usually recommended to loop array backwards when you intend to delete item from the array as each deletion will move the index of the rest of the array up by 1, which causes problem:

Sub Remove_Other_Users_from_Shared_Workbook()

    Dim UsrList()

    UsrList = ThisWorkbook.UserStatus

    For i = UBound(UsrList, 1) To 1 Step -1
        If UsrList(i, 1) <> Application.UserName Then ThisWorkbook.RemoveUser i
    Next
    
End Sub

You are not able to add End If to your If statement because you have a line of code after Then which makes this a 1-line statement. If you do want to put End If then you must move ThisWorkbook.RemoveUser i to the next line like this:

Sub Remove_Other_Users_from_Shared_Workbook()

    Dim UsrList()

    UsrList = ThisWorkbook.UserStatus

    For i = UBound(UsrList, 1) To 1 Step -1
        If UsrList(i, 1) <> Application.UserName Then 
            ThisWorkbook.RemoveUser i
        End If
    Next
    
End Sub

Note: If you only have 1 line of code in the Then branch then your current code is perfectly fine.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM