GetSetting Function
Returns a registry key setting value from the Windows registry.
Syntax
GetSetting(appname, section, key[, default])
Parameters
appname(Required):Stringexpression containing the name of the application or project whose key setting is requested. On Windows, this is a subkey underHKEY_CURRENT_USER\Software\VB and VBA Program Settings.section(Required):Stringexpression containing the name of the section where the key setting is found.key(Required):Stringexpression containing the name of the key setting to return.default(Optional): Expression containing the value to return if no value is set in the key setting. If omitted, default is assumed to be a zero-length string ("").
Return Value
Returns a String containing the value of the specified registry key. If the key doesn't exist and no default is provided, returns an empty string.
Remarks
The GetSetting function retrieves settings from the Windows registry that were previously saved using the SaveSetting statement. The settings are stored in the application's subkey under:
HKEY_CURRENT_USER\Software\VB and VBA Program Settings\appname\section
- If the registry key doesn't exist,
GetSettingreturns the default value (or "" if no default specified) GetSettingonly works with theHKEY_CURRENT_USERregistry hive- For more advanced registry access, use Windows API functions like
RegOpenKeyExandRegQueryValueEx - The
appname,section, andkeyparameters are case-insensitive GetSettingis designed to work withSaveSetting,DeleteSetting, andGetAllSettings- On non-Windows platforms, behavior may vary or be unsupported
Typical Uses
- Application Configuration: Retrieve user preferences and application settings
- User Preferences: Load window positions, sizes, and UI state
- Recent Files: Get most recently used files or paths
- Database Connections: Retrieve connection strings and server names
- Feature Toggles: Load feature flags and experimental settings
- Localization: Get language and regional preferences
Basic Usage Examples
' Example 1: Get a simple setting with default
Dim userName As String
userName = GetSetting("MyApp", "User", "Name", "Guest")
' Example 2: Get window position
Dim formLeft As String
formLeft = GetSetting("MyApp", "Window", "Left", "0")
' Example 3: Get setting without default
Dim lastFile As String
lastFile = GetSetting("MyApp", "Recent", "File1")
' Example 4: Get database connection
Dim connString As String
connString = GetSetting("MyApp", "Database", "ConnectionString", "")
Common Patterns
' Pattern 1: Load form position and size
Private Sub Form_Load()
Me.Left = CLng(GetSetting("MyApp", "MainForm", "Left", "0"))
Me.Top = CLng(GetSetting("MyApp", "MainForm", "Top", "0"))
Me.Width = CLng(GetSetting("MyApp", "MainForm", "Width", "6000"))
Me.Height = CLng(GetSetting("MyApp", "MainForm", "Height", "4500"))
End Sub
' Pattern 2: Check if setting exists
Function SettingExists(app As String, section As String, key As String) As Boolean
Dim marker As String
marker = String$(10, "X")
SettingExists = (GetSetting(app, section, key, marker) <> marker)
End Function
' Pattern 3: Get with type conversion
Dim showTips As Boolean
showTips = CBool(GetSetting("MyApp", "Options", "ShowTips", "True"))
' Pattern 4: Get recent file list
Dim i As Integer
Dim recentFiles() As String
ReDim recentFiles(1 To 10)
For i = 1 To 10
recentFiles(i) = GetSetting("MyApp", "Recent", "File" & i, "")
If recentFiles(i) = "" Then Exit For
Next i
' Pattern 5: Get connection info
Dim server As String, database As String
server = GetSetting("MyApp", "Database", "Server", "localhost")
database = GetSetting("MyApp", "Database", "Name", "MyDB")
' Pattern 6: Get user preference with validation
Dim fontSize As Integer
fontSize = CInt(GetSetting("MyApp", "UI", "FontSize", "10"))
If fontSize < 8 Or fontSize > 72 Then fontSize = 10
' Pattern 7: Get setting in With block
With Form1
.BackColor = CLng(GetSetting("MyApp", "Colors", "Background", "16777215"))
End With
' Pattern 8: Conditional loading
If GetSetting("MyApp", "Options", "AutoSave", "False") = "True" Then
EnableAutoSave
End If
' Pattern 9: Get multiple related settings
Dim smtp As String, port As String, useTLS As String
smtp = GetSetting("MyApp", "Email", "SMTPServer", "smtp.gmail.com")
port = GetSetting("MyApp", "Email", "Port", "587")
useTLS = GetSetting("MyApp", "Email", "UseTLS", "True")
' Pattern 10: Safe retrieval with error handling
On Error Resume Next
Dim value As String
value = GetSetting("MyApp", "Config", "Setting", "DefaultValue")
If Err.Number <> 0 Then
value = "DefaultValue"
Err.Clear
End If
On Error GoTo 0
Advanced Usage Examples
' Example 1: Settings manager class
Public Class AppSettings
Private Const APP_NAME As String = "MyApplication"
Public Function GetStringSetting(section As String, key As String, _
Optional defaultValue As String = "") As String
GetStringSetting = GetSetting(APP_NAME, section, key, defaultValue)
End Function
Public Function GetIntegerSetting(section As String, key As String, _
Optional defaultValue As Integer = 0) As Integer
Dim value As String
value = GetSetting(APP_NAME, section, key, CStr(defaultValue))
On Error Resume Next
GetIntegerSetting = CInt(value)
If Err.Number <> 0 Then GetIntegerSetting = defaultValue
End Function
Public Function GetBooleanSetting(section As String, key As String, _
Optional defaultValue As Boolean = False) As Boolean
Dim value As String
value = GetSetting(APP_NAME, section, key, CStr(defaultValue))
GetBooleanSetting = CBool(value)
End Function
End Class
' Example 2: Application configuration loader
Private Sub LoadApplicationConfig()
Dim config As New Collection
config.Add GetSetting("MyApp", "Paths", "Data", App.Path & "\Data"), "DataPath"
config.Add GetSetting("MyApp", "Paths", "Export", App.Path & "\Export"), "ExportPath"
config.Add GetSetting("MyApp", "Paths", "Temp", Environ$("TEMP")), "TempPath"
config.Add GetSetting("MyApp", "Database", "Server", "localhost"), "DBServer"
config.Add GetSetting("MyApp", "Database", "Name", "AppDB"), "DBName"
config.Add GetSetting("MyApp", "Options", "AutoBackup", "True"), "AutoBackup"
config.Add GetSetting("MyApp", "Options", "BackupInterval", "60"), "BackupInterval"
Set g_AppConfig = config
End Sub
' Example 3: Multi-user profile system
Public Function LoadUserProfile(userName As String) As UserProfile
Dim profile As New UserProfile
Dim section As String
section = "User_" & userName
With profile
.FullName = GetSetting("MyApp", section, "FullName", userName)
.Email = GetSetting("MyApp", section, "Email", "")
.Role = GetSetting("MyApp", section, "Role", "User")
.Theme = GetSetting("MyApp", section, "Theme", "Default")
.Language = GetSetting("MyApp", section, "Language", "en-US")
.LastLogin = GetSetting("MyApp", section, "LastLogin", "")
End With
LoadUserProfile = profile
End Function
' Example 4: MRU (Most Recently Used) manager
Public Class MRUManager
Private Const MAX_MRU As Integer = 10
Private Const APP_NAME As String = "MyApp"
Private Const SECTION As String = "MRU"
Public Function GetMRUList() As Collection
Dim mruList As New Collection
Dim i As Integer
Dim item As String
For i = 1 To MAX_MRU
item = GetSetting(APP_NAME, SECTION, "Item" & i, "")
If Len(item) > 0 Then
mruList.Add item
Else
Exit For
End If
Next i
Set GetMRUList = mruList
End Function
Public Sub AddMRUItem(filePath As String)
Dim mruList As Collection
Dim i As Integer
Dim item As String
Set mruList = GetMRUList()
' Remove if already exists
For i = 1 To mruList.Count
If StrComp(mruList(i), filePath, vbTextCompare) = 0 Then
mruList.Remove i
Exit For
End If
Next i
' Add to top
mruList.Add filePath, , 1
' Save back
For i = 1 To mruList.Count
If i > MAX_MRU Then Exit For
SaveSetting APP_NAME, SECTION, "Item" & i, mruList(i)
Next i
End Sub
End Class
Error Handling
GetSetting generally doesn't raise errors, but returns the default value if the setting doesn't exist:
- No Error: If the registry key doesn't exist, returns default (or "" if no default)
- No Error: If appname, section, or key is empty, returns default value
- Type Mismatch: Can occur when converting returned String to another type (e.g.,
CInt) - Registry Access: On systems where registry access is restricted, may return defaults
' Safe retrieval with type conversion
On Error Resume Next
Dim timeout As Integer
timeout = CInt(GetSetting("MyApp", "Network", "Timeout", "30"))
If Err.Number <> 0 Then
timeout = 30
Err.Clear
End If
On Error GoTo 0
Performance Considerations
- Registry Access: Each call accesses the Windows registry, which is slower than memory access
- Caching: Consider caching frequently used settings in memory
- Startup Time: Loading many settings at startup can slow application initialization
- Batch Loading: Use
GetAllSettingsto retrieve all settings in a section at once for better performance
Best Practices
- Use Defaults: Always provide sensible default values
- Validate Values: Validate retrieved settings before using them
- Cache Settings: Load settings once and cache them for the session
- Consistent Naming: Use consistent naming conventions for
appname,section, andkey - Error Handling: Use error handling when converting string values to other types
- Cleanup: Use
DeleteSettingto remove obsolete settings - Documentation: Document all registry keys used by your application
Comparison with Other Registry Functions
| Function | Purpose | Returns |
|---|---|---|
GetSetting |
Get single registry value | String |
GetAllSettings |
Get all values in a section | Variant array |
SaveSetting |
Save registry value | N/A (statement) |
DeleteSetting |
Delete registry key/section | N/A (statement) |
Platform Compatibility
- Windows: Full support, uses
HKEY_CURRENT_USERregistry hive - Other Platforms: May use alternative storage mechanisms or be unsupported
- Registry Location:
HKEY_CURRENT_USER\Software\VB and VBA Program Settings\appname\section\key
Limitations
- Only accesses
HKEY_CURRENT_USERhive (use Windows API for other hives) - Returns
Stringtype only (requires conversion for other types) - No direct way to check if a key exists (use unique default value trick)
- Limited to VB's registry structure (use Windows API for custom locations)
- No support for
REG_BINARYor other complex registry types - Settings are user-specific, not machine-wide
Related Functions
GetAllSettings: Returns all key settings and their values from a registry sectionSaveSetting: Saves or creates an application entry in the Windows registryDeleteSetting: Deletes a section or key setting from the Windows registryEnviron: Returns the string associated with an environment variableCommand: Returns the argument portion of the command lineApp.Path: Returns the path where the application executable is located