Many applications use settings the user can change. It is convenient for the
user if these settings are stored so they are used each time Excel is started.
There are a number of methods to achieve this. The first method demonstrated
here is by using a text file. There are various options where to store this text
file, like e.g. the Windows folder or the Documents and settings folder
pertaining to the user currently logged on to the system. But the simplest
location is where the add-in file itself is stored.
The sample code below stores the "settings" in a file called xlutil01.ini in
that location:
Listing 5
OptionExplicit
Dim
msInipath AsString Public gsLanguage AsString Public gsMessage AsString
Sub ReadIni() Dim lFile AsLong lFile = FreeFile 'Use folder the add-in is stored in msInipath = ThisWorkbook.Path & "\" OnErrorResumeNext Open
msInipath & "xlutil01.ini" ForInputAs #lFile 'If File does not exist, create
it If Err = 53 Then CreateIni ExitSub EndIf Input #lFile, gsLanguage, gsMessage Close #lFile bVarsOK = True OnErrorGoTo 0 EndSub
Sub CreateIni() 'Create ini file using default settings gsLanguage = "English" gsMessage = "Your default message." WriteIni EndSub
SubWriteIni() Dim lFile AsLong lFile = FreeFile Open
msInipath & "xlutil01.ini" ForOutputAs #lFile Write #lFile, gsLanguage, gsMessage Close #lFile EndSub
Sub ChangeSettings() IfNot bVarsOK Then ReadIni gsLanguage = InputBox("Enter the language", "xlUtil01", gsLanguage) gsMessage = InputBox("Enter your message", "xlUtil01", gsMessage) If gsLanguage = "" Or gsMessage = "" Then ReadIni MsgBox "Changes cancelled!", vbOKOnly + vbInformation ExitSub Else WriteIni EndIf EndSub
Another method with which settings can be saved is by using the registry.
There are two VBA functions for this goal: GetSetting and SaveSetting. These
will create entries to write to in the following registry location:
“My Computer\HKEY_CURRENT_USER\Software\VB and VBA Program Settings\”.
The code below demonstrates the mechanisms.
Listing 6
OptionExplicit
Public gsShortCutKey AsString'Holds the shortcutkey PublicConst gsRegKey AsString = "xlUtilDemo" 'The registry entries' name
Sub GetSettings() 'Get the shortcutkey, use "n" if anything goes wrong gsShortCutKey = GetSetting(gsRegKey, "Settings", "ShortCutKey", "n") EndSub
Sub SaveSettings() 'Save the shortcutkey to the registry SaveSetting gsRegKey, "Settings", "ShortCutKey", gsShortCutKey EndSub
Sub Deletesettings() 'Remove all registry entries belonging to this application DeleteSetting gsRegKey EndSub
Sub ChangeSettings() GetSettings gsShortCutKey = InputBox("Please enter a new shortcutkey", , gsShortCutKey) If gsShortCutKey = "" ThenExitSub gsShortCutKey = Left(gsShortCutKey, 1) SaveSettings EndSub
To remove the registry entry, run the sub "DeleteSettings"
The figure below shows the results in the registry
Screenshot of the register editor showing the new entry.