Dzwebs.Net

撰写电脑技术杂文十余年

Office应用之VBA操作INI文件代码示例

Admin | 2009-2-14 18:59:31 | 被阅次数 | 10977

温馨提示!

如果未能解决您的问题,请点击搜索;登陆可复制文章,点击登陆

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

  注:代码来自网络!


该杂文来自: Excel杂文

上一篇:Excel出现“公式中的单元格引用指向的公式结果,

下一篇:使用TRIMMEAN函数去除几个最高分和几个最低分之后

网站备案号:

网站备案号:滇ICP备11001339号-7

版权属性:

Copyright 2007-2021-forever Inc. all Rights Reserved.

联系方式:

Email:dzwebs@126.com QQ:83539231 访问统计