vba读写ini配置文件

原创文章,欢迎转载:http://miao.blog/article/vba-ini

' read and write ini file api
Public 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
Public 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 Const MAXCOUNT As Long = 1024

Private ini_file_path As String
 
' read
Function ReadStringFromIni(ByVal FileName As String, ByVal section As String, ByVal key As String) As String
    Dim x As Long
    Dim xBuff As String * MAXCOUNT
    GetPrivateProfileString section, key, "", xBuff, MAXCOUNT, FileName
    x = InStr(xBuff, Chr(0))
    ReadStringFromIni = Trim(Left(xBuff, x - 1))
End Function
 
' write
Sub WriteStringToIni(ByVal FileName As String, ByVal section As String, ByVal key As String, ByVal value As String)
    Dim xBuff As String * MAXCOUNT
    xBuff = value + Chr(0)
    WritePrivateProfileString section, key, xBuff, FileName
End Sub


Function GetIniVal(section As String, key As String)
    ini_file_path = "C:\Users\" & Environ("username") & "\Deloitte_AA_Admin_Helper.ini"
    GetIniVal = ReadStringFromIni(ini_file_path, section, key)
End Function

Sub SetIniVal(section As String, key As String, value As String)
    ini_file_path = "C:\Users\" & Environ("username") & "\Deloitte_AA_Admin_Helper.ini"
    Call WriteStringToIni(ini_file_path, section, key, value)
End Sub
推荐阅读
使用VBA调用Outlook发送邮件
VBA发送GET、POST请求的方法
评论