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要实现md5必须引用外部库,导致vba程序交付安装不是很方便。很多时候我们并不是想要取真正的md5,只是取一个加密字符串,比如保存密码的时候。本文中的代码直接利用windows系统内置命令certutil -hashfile实现了一种变相的md5函数。代码要读写本地文件两次,因此效率不高,不过在登陆验证一下密码等场景并没有影响。
评论