如何为Excel文件的不同用户设置不同的权限

时间:2018-04-17 12:38:01

标签: vba login userform

也许你可以帮我解决这个问题:

我正在尝试为一个excel表设置不同类型的权限。 例如,将有一个具有所有权限的管理员和一个访客,如何只允许更改一系列单元格。 我开始设置2种不同类型的登录,一个用于管理员工作正常但是一个用于访客根本没有。 我在这里做错了什么?

Ps:我刚开始学习VBA☺

Private Sub CommandButton1_Click()
   Dim objTargetWorksheet As Worksheet
'Gast
  If (TextBox1.Value = "Gast" And TextBox2.Value = "123") _
Or (TextBox1.Value = "Amy" And TextBox2.Value = "345") _
Or (TextBox1.Value = "Paul" And TextBox2.Value = "456") Then
Me.Hide: Application.Visible = True

For Each objTargetWorksheet In ActiveWorkbook.Worksheets
  If objTargetWorksheet.Name = TextBox1.Value Then
    Range("K3:K50").Locked = True
    ActiveSheet.Protect Password:="12345", Contents:=True
  Else
   Range("K3:K50").Locked = True
    ActiveSheet.Protect Password:="12345", Contents:=True

  End If
Next
'Admin
ElseIf TextBox1.Value = "Admin" Then
    If TextBox2.Value = "" Then
        MsgBox "Please Input the Password"
    ElseIf TextBox2.Value = "123" Then
        Me.Hide: Application.Visible = True
    Else
        MsgBox "Please Input the right User Name and the right Password"
    End If


  Else
    MsgBox "Please input the right user name and the right password"
  End If
End Sub

Private Sub CommandButton2_Click()
  ThisWorkbook.Application.Quit
End Sub



Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
  ThisWorkbook.Application.Quit
End Sub

1 个答案:

答案 0 :(得分:0)

您需要参考您正在处理的工作表。

For Each objTargetWorksheet In ActiveWorkbook.Worksheets
  If objTargetWorksheet.Name = TextBox1.Value Then
    objTargetWorksheet.Range("K3:K50").Locked = True
    objTargetWorksheet.Protect Password:="12345", Contents:=True
  Else
    objTargetWorksheet.Range("K3:K50").Locked = True
    objTargetWorksheet.Protect Password:="12345", Contents:=True
  End If
Next

更新:默认情况下,单元格已锁定,因此您必须在保护工作表之前解锁它们。试试这个:

For Each objTargetWorksheet In ActiveWorkbook.Worksheets
  If objTargetWorksheet.Name = TextBox1.Value Then
    objTargetWorksheet.Cells.Locked = False
    objTargetWorksheet.Range("K3:K50").Locked = True
    objTargetWorksheet.Protect Password:="12345", Contents:=True
  Else
    objTargetWorksheet.Cells.Locked = False 
    objTargetWorksheet.Range("K3:K50").Locked = True
    objTargetWorksheet.Protect Password:="12345", Contents:=True
  End If
Next