22 | 02 | 2017

Write/Read Values From INI file

Different users can have different settings. A INI file is very useful to store paths or other values.

First create a new CLASS Module called INIengine

Option Explicit

Private Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" ,_
(ByVal lpApplicationName As String, ByVallpKeyName As Any, ByVal lpDefault As String, ,_
ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long
Private Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" ,_
(ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpStringAsAny, ByVal lpFileNameAsString) As Long
Private_m_FilePath
 
'--------------------------------------------------------------------------------
 
Public Property Let FilePath(newval)
m_FilePath = newval
End Property
'--------------------------------------------------------------------------------
 
Public Property Get FilePath()
 
FilePath = m_FilePath
 
End Property
'--------------------------------------------------------------------------------
Public Function ReadValue(GroupNameAsString, KeyNameAsString)
 
On Error GoTo errorhandler
'Use this function to read values from the INIfile
'If our file path variable isnt set send back an error value to the callingprocedure
If m_FilePath = "" Then ReadValue = -287: ExitFunction
Dim ret As String
ret = String(255, 32)
rc = GetPrivateProfileString(GroupName, KeyName, "Default", ret, 255, m_FilePath)
If rc <> 0 Then ret = Left$(ret, rc)
ReadValue = ret
errorhandler:
Exit Function
End Function
 
'--------------------------------------------------------------------------------
 
Public Function WriteValue(GroupName As String, KeyName As String, value As String)
 
'UsethisfunctiontowritevaluestotheINIfile
If m_FilePath = "" Then WriteValue = -287: ExitFunction
rc = WritePrivateProfileString(GroupName, KeyName, value, m_FilePath)
WriteValue = rc
End Function
 

To write values to the INI file use:

Sub WritetoINIfile()
'Initilize the CLass
Dim INI As New INIengine
Dim values As Variant
 
'Set the file path
INI.FilePath = ("c:\windows\Sample.ini")
 
'Write Value to the INI file
values = INI.WriteValue("PATH", "Workbookpath", "C:\Sample.xls")
 
End Sub
To read values to the INI file use:

Sub ReadfromINIfile()
'Initilize the CLass
Dim INI As New INIengine
Dim values As Variant
 
'Set the file path
INI.FilePath = ("c:\windows\Sample.ini")
 
'Read Value from the INI file
values = INI.ReadValue("PATH", "Workbookpath")
End Sub
 
 
Login

Sign up now and upload your code to the website.

Help us to continue.....
Statistics
Articles View Hits
2174898
Latest Articles