Search code examples
excelvbaregistryuserform

How to initialize useform checkboxes with values from registry


I have a checkbox on my userform. When I click it, the value is set to "True" and the setting is stored in registry. When I uncheck it, its being set to "False" and setting again is set in registry.

The code for check box click event:

Dim CheckBox_Check As String
CheckBox_Check = GetSetting(appname:="APPLICATION", section:="SECTION", Key:="CHECKBOXKEY")

If CheckBox_Check = False Then
    CheckBox.Value = True
    SaveSetting "APPLICATION", "SECTION", "CHECKBOXKEY", "True"
    Exit Sub
ElseIf CheckBox_Check = True Then
    CheckBox.Value = False
    SaveSetting "APPLICATION", "SECTION", "CHECKBOXKEY", "False"
    Exit Sub
End If

The code above works well, but I have a great issue with initializing the userform with checkbox setting (true or false). When I use the following code on userform_initialize:

CheckBox.Value = GetSetting(appname:="APLIKACJA", section:="SECTION", Key:="CHECKBOXKEY")

Then when it needs to set checkbox to true, it goes all the way through "checkbox click" sub, and it simply does not work. Userform initializes only with false values.

Can somebody help me sort it out? I am trying to achieve the following goals:

1) To be able to set checkbox to "checked" "unchecked" and store those settings in registry.

2) Initialize userform with "checked" "unchecked" status based on registry values.


Solution

  • Try this approach, please:

    Sub testValFromRegistry()
    Dim strInit As String
       strInit = GetSetting("APLIKACJA", "SECTION", "CHECKBOXKEY", "No settings...")
       Application.EnableEvents = False
        If strInit = "No settings..." Then
             CheckBox.value = False
        Else
             CheckBox.value = CBool(strInit)
        End If
       Application.EnableEvents = True
    End Sub
    

    You write "True" in Registry, which is a String. It must be transformed in Boolean... Otherwise, it is all the time False.