推荐的方式来读写VBA .ini文件方式、文件、VBA、ini

2023-09-09 21:23:28 作者:手心里的温柔

是VBA可读写INI文件的任何方法?我知道我可以使用;

Are any methods available in VBA to read and write INI files? I know I could use;

Open "C:\test.ini" For Input As #1

...和分析数据。相反,我想看看有什么工具都已经上市。

...and parse the data. Instead I am trying to see what tools are already available.

我知道在C#中,你可以做...

I know in C# you can do...

 using INI;
 INIFile ini = new INIFile("C:\test.ini");

有一种等效的VBA?

我在MS Access 2003 VBA尝试这一点。

I am attempting this in MS Access 2003 VBA.

推荐答案

下面是我们使用一些code片段,它应该帮助你的想法。这些程序使用API​​调用。两个功能都包含读/写一个字符串设定为在INI文件中的特定部分。

Here are some code snippets that we use, it should help you to get the idea. These routines use the API calls. Two functions are included to read / write a string setting to a specific section in the ini file.

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 IniFileName() As String
  IniFileName = "c:\[yourpath here]\settings.ini"
End Function


Private Function ReadIniFileString(ByVal Sect As String, ByVal Keyname As String) As String
Dim Worked As Long
Dim RetStr As String * 128
Dim StrSize As Long

  iNoOfCharInIni = 0
  sIniString = ""
  If Sect = "" Or Keyname = "" Then
    MsgBox "Section Or Key To Read Not Specified !!!", vbExclamation, "INI"
  Else
    sProfileString = ""
    RetStr = Space(128)
    StrSize = Len(RetStr)
    Worked = GetPrivateProfileString(Sect, Keyname, "", RetStr, StrSize, IniFileName)
    If Worked Then
      iNoOfCharInIni = Worked
      sIniString = Left$(RetStr, Worked)
    End If
  End If
  ReadIniFileString = sIniString
End Function

Private Function WriteIniFileString(ByVal Sect As String, ByVal Keyname As String, ByVal Wstr As String) As String
Dim Worked As Long

  iNoOfCharInIni = 0
  sIniString = ""
  If Sect = "" Or Keyname = "" Then
    MsgBox "Section Or Key To Write Not Specified !!!", vbExclamation, "INI"
  Else
    Worked = WritePrivateProfileString(Sect, Keyname, Wstr, IniFileName)
    If Worked Then
      iNoOfCharInIni = Worked
      sIniString = Wstr
    End If
    WriteIniFileString = sIniString
  End If
End Function
 
精彩推荐
图片推荐