用VBA Dictionary做一个简单的用户系统



  • 给大家建议这篇大佬Paul Kelly的文章关于VBA Dictionary的文章,讲的非常好https://excelmacromastery.com/vba-dictionary

    首先,要使用Dictionary,我们需要勾选Microsoft Scripting Runtime这个library

    36226212-148a-4286-8f9d-7610af80b74a-image.png

    6c1d757a-e524-4bc3-a876-13670c7b36af-image.png



  • 在Excel里面输入两个按钮:
    3310e627-4718-44b2-9f0c-ec7538202002-image.png

    然后开始我们的操作,首先定义UserDataBase这个字典

    Dim UserDataBase As New Dictionary
    

    注册新的用户

    Sub Register()
    
    Dim name As String, password As String
    ' 让用户输入用户名
    name = Application.InputBox("Please input your user name")
    ‘如果用户名存在
    If UserDataBase.Exists(name) Then
        MsgBox ("This user has registered!")
    Else
    ‘如果用户名不存在,那么加入用户名到字典
        password = Application.InputBox("Please input your Password")
        UserDataBase(name) = password
    End If
    
    End Sub
    


  • 登入

    Sub login()
    
    Dim name As String, password As String
    '输入用户名
    name = Application.InputBox("Please input your name")
    ‘如果用户名存在,且和密码可以匹配,那么问候这个人
    If UserDataBase.Exists(name) Then
    password = Application.InputBox("Please input your Password")
        If password = UserDataBase(name) Then
            MsgBox ("Hello and welcome, " & name)
        Else
    '如果不存在,亲切地提示密码错误
            MsgBox ("Your password is so fucking wrong")
        End If
    Else
    ‘如果用户名不存在,让他注册
        MsgBox ("This user has not registered! Please register instead")
    End If
    
    End Sub
    


  • 然后给我们的按钮赋予宏
    7cb518e4-bfe1-4ec4-ae5f-abdfa7a799da-image.png
    点击注册
    167a2f96-dffa-42d4-b234-8ef39967af31-image.png
    29baa5e6-ac07-4c61-ab22-bb16fee8a691-image.png

    点击登入
    7c16f92e-c31f-4343-b685-d644875b7854-image.png

    f02d0460-3830-4f10-814c-169356e5593b-image.png
    因为这个密码对大小写敏感,提示密码错误
    257e29db-5016-4cc9-b5bc-89a25b6f63f9-image.png


Log in to reply