如何为某些用户打开excel文件读写,为其他用户打开readonly

时间:2014-04-09 08:55:25

标签: excel excel-vba vba

我有一个excel文件,我的所有同事都必须具有读取权限,但只有少数人可能具有写入权限。

我尝试在workbook_open中引入一个测试用户的程序,并根据它来决定如何打开文件。我知道这不能直接工作,所以我尝试访问一个具有更改只读状态的过程的加载项。

Private Sub Workbook_Open()
    users = Environ("USERNAME")
    Select Case users
        Case "chris": MsgBox "ok"
        Case "david": MsgBox "ok"
        Case "sam": MsgBox "ok"            
        Case Else: Application.Run ("read_only")
    End Select
End Sub

这是Addin

中的子功能
Sub read_only()
   file_name = ActiveWorkbook.Path & "\" & ActiveWorkbook.Name
   Status = ActiveWorkbook.readonly

   ActiveWorkbook.Close ' (the problem is here because also this sub stops when my workbook closes)
   If Status = False Then
       Workbooks.Open fileName:=file_name, readonly:=True 
    Else
       Workbooks.Open fileName:=file_name, readonly:=False  
   End If
End Sub

有谁知道如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

你可以直接这样做:)

试试这个

Private Sub Workbook_Open()
Users = Environ("USERNAME")
    Select Case Users
        Case "chris": MsgBox "ok"
        Case "david": MsgBox "ok"
        Case "sam": MsgBox "ok"
        Case Else
        Application.DisplayAlerts = False
        On Error Resume Next
       'may already be read only
        If ThisWorkbook.Path <> vbNullString Then ThisWorkbook.ChangeFileAccess xlReadOnly
        On Error GoTo 0
        Application.DisplayAlerts = True
    End Select
End Sub