VBA – 如何指定有效的用户执行某些操作

在closures之前我已经创build了一些强制的单元格,并希望有一些用户来强制强制的单元格。 从这里find这些代码,试图编辑代码,但它不起作用。

希望有人能解释给我。 u,sers1,u,sers2是不需要填写强制单元格的用户,他们可以closures工作簿而将单元格留空。 在Excel中的用户名格式是u, ser1

感谢任何build议和帮助。

 Function IsInvalidUser() As Boolean Dim asUsers() As String asUsers = Split("u, ser1.u, ser2", ".") IsInvalidUser = IsError(Application.Match(Environ("UserName"), asUsers, 0)) End Function Private Sub Workbook_BeforeClose(Cancel As Boolean) If Not (IsInvalidUser) And Cells(2, 8).Value = "" Then MsgBox "Cell H2 requires user input", vbInformation, "Please filled up the mandatory cells" Cancel = True ElseIf Not (IsInvalidUser) And Cells(4, 4).Value = "" Then MsgBox "Cell D4 requires user input", vbInformation, "Please filled up the mandatory cells" Cancel = True End If End Sub 

看起来arrays很难保持。 我会在隐藏的工作表上使用一个列表。 一个Scripting.Dictionary也可以很好地工作,并有能够比较文本的额外优势。

 Function IsValidUser() As Boolean With CreateObject("Scripting.Dictionary") .CompareMode = vbTextCompare .Add "u, ser1", vbNullString .Add "u, ser2", vbNullString IsValidUser = .Exists(Environ("UserName")) End With End Function Private Sub Workbook_BeforeClose(Cancel As Boolean) If Not IsValidUser Then If Cells(2, 8).Value = "" Then MsgBox "Cell H2 requires user input", vbInformation, "Please filled up the mandatory cells" ElseIf Cells(4, 4).Value = "" Then MsgBox "Cell D4 requires user input", vbInformation, "Please filled up the mandatory cells" End If Cancel = True End If End Sub 

注意:我改变了逻辑来检查有效的用户。