VBA操作INI配置文件源代码

分类:代码, 博客 标签:

一般程序都有一些配置或者设置选项,而这些参数一般是保存为INI配置文件,如何使用VBA操作这些INI格式的配置文件是比较常用的,这里水文工具集提供一个操作INI文件的源代码:

Option Explicit
'================================
' VBA操作INI配置文件
' 
' http://www.cnhup.com
'================================
Private Declare Function _
GetPrivateProfileString Lib "kernel32" _
 Alias "GetPrivateProfileStringA" _
 (ByVal lpApplicationName As String, _
 ByVal lpKeyName 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 lpString As Any, _
 ByVal lpFileName As String) As Long

Public Function ReadFromIni( _
 ByVal IniFile As String, _
 ByVal Section As String, _
 ByVal Key As String, _
 ByVal DefaultValue As String) As String
    
    Dim strRtn As String
    strRtn = Space(256)
    
    Dim lngRtn As Long
    lngRtn = GetPrivateProfileString(Section, Key, DefaultValue, strRtn, 255, IniFile)
    
    If lngRtn > 0 Then
        strRtn = Trim(strRtn)
        ReadFromIni = Mid(strRtn, 1, Len(strRtn) - 1)
    Else
        ReadFromIni = DefaultValue
    End If

End Function

Public Sub WriteIntoIni( _
 ByVal IniFile As String, _
 ByVal Section As String, _
 ByVal Key As String, _
 ByVal Value As String)
    
    Dim lngRtn As Long
    lngRtn = WritePrivateProfileString(Section, Key, Value, IniFile)
    
    If lngRtn > 0 Then
    Else
        Call Err.Raise(-1, "IniFileUtil.WriteIntoIni", "Failed to write")
    End If

End Sub


分类:代码, 博客 标签:

发表评论

You must be logged in to post a comment.