首页 > Excel专区 > Excel函数 >

excel VBA 如何读取和写入 INI 文件

Excel函数 2021-11-17 14:06:16

我们写一些小代码时,有时需要将部分配置信息保存在用户的电脑上,一般可以采取保存在注册表,XML 文件和 INI 文件等方法。这几种方法各有优缺点,我觉得当配置信息简单时,保存在 INI 文件还是很高效的。这里提供一段小代码,用于读取和写入 INI 文件

excel VBA 如何读取和写入 INI 文件
excel VBA 如何读取和写入 INI 文件

具体代码:

Option Explicit
#If Win64 Then
Public Declare PtrSafe 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 PtrSafe Function WritePrivateProfileString _
Lib "kernel32" Alias "WritePrivateProfileStringA" ( _
ByVal lpApplicationName As String, ByVal lpKeyName As Any, _
ByVal lpString As Any, ByVal lpFileName As String) As Long
#Else
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
#End If

Public Const MAXCOUNT As Long = 256

'********************************************************************
'用途: 读取指定的键值
'返回值: 指定的键值
'参数名 说明
'FileName Ini 文件全名(含路径)
'Section 节点的名称
'Key 键名
'********************************************************************
Public 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

'********************************************************************
'用途: 写入指定的键值
'参数名 说明
'FileName Ini 文件全名(含路径)
'Section 节点的名称
'Key 键名
'Value 需要写入的键值
'********************************************************************
Public 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

注意:代码可用于 32 位和 64 位 Office; 请将下载后的文件解压到同一文件夹

1文件名称 1下载链接
INIFileReadWrite.zip http://pan.baidu.com/s/1hqCCVdi


标签: VBA教程

office教程网 Copyright © 2016-2020 https://www.office9.cn. Some Rights Reserved.