INI文件读写VBA代码

Option Explicit
                        
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

以下代码简单演示如何使用上述ReadFromIni、WriteIntoIni两个函数

Option Explicit

Public Sub Main()

On Error GoTo Err_Handling

    Dim strIniFile As String
    strIniFile = ActiveWorkbook.Path & "\example.ini"

    Dim strSection As String
    strSection = "Application"
    
    Dim strKey As String
    strKey = "Version"
    
    Dim strValue As String
    strValue = "1.0.30"
    
    Call IniUtil.WriteIntoIni(strIniFile, strSection, strKey, strValue)
    
    strValue = IniUtil.ReadFromIni(strIniFile, strSection, strKey, "")
    Call MsgBox("Version = " & strValue, vbInformation + vbOKOnly, ET.ActiveWorkbook.Name)
Exit_Door:
    Exit Sub
    
Err_Handling:
    Call MsgBox(Err.Number & "-" & Err.Description, vbExclamation + vbOKOnly, ET.ActiveWorkbook.Name)
    Resume Exit_Door

posted on 2012-02-28 11:03  Jack.leung 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/jack-liang/archive/2012/02/28/2371158.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值