使用的词语在Excel中使用VBA System.PrivateProfileString私人档案字符串
如果您不想使用API函数,则可以使用Words对象库来读写私有配置文件字符串。
单词System.PrivateProfileString可以读取和写入INI文件和注册表。
在Word以外的其他应用程序中,您必须添加对Words对象库的引用。
您可以通过打开Visual Basic编辑器(VBE)来添加引用并激活您的VB项目。然后,选择“工具,引用…”,然后选中“ Microsoft Word x.x对象库”选项。
将信息写入INI文件
通过下面的宏,您可以将信息保存在文本文件中:
Function SetIniSetting(FileName As String, Section As String, _ Key As String, KeyValue) As Boolean Dim wd As Word.Application SetIniSetting = False Set wd = New Word.Application ' create the Word application object On Error Resume Next wd.System.PrivateProfileString(FileName, Section, Key) = CStr(KeyValue) On Error GoTo 0 Set wd = Nothing ' destroy the Word application object SetIniSetting = True End Function
使用这样的宏将值100保存在MySectionName部分的文件C:\ FolderName \ FileName.ini中,以保存键TestValue:
MyBooleanVar = SetIniSetting(“ C:\ FolderName \ FileName.ini”,“ MySectionName”,“ TestValue”,100)
文本文件将如下所示:
TestValue = 100
从INI文件中读取信息
使用下面的宏,您可以从文本文件中读取信息:
Function GetIniSetting(FileName As String, Section As String, _ Key As String) As String Dim wd As Word.Application GetIniSetting = "" Set wd = New Word.Application ' create the Word application object On Error Resume Next GetIniSetting = wd.System.PrivateProfileString(FileName, Section, Key) On Error GoTo 0 Set wd = Nothing ' destroy the Word application object End Function
使用这样的宏从文件C:\ FolderName \ FileName.ini返回MySectionName部分中的键TestValue的值:
MyStringVar = GetIniSetting("C:\FolderName\FileName.ini", _ "MySectionName", "TestValue")
===
将信息写入注册表*通过下面的宏,您可以将信息保存在注册表中:
Function SetRegistrySetting(Section As String, _ Key As String, KeyValue) As Boolean Dim wd As Word.Application SetRegistrySetting = False Set wd = New Word.Application ' create the Word application object On Error Resume Next wd.System.PrivateProfileString("", Section, Key) = CStr(KeyValue) On Error GoTo 0 Set wd = Nothing ' destroy the Word application object SetRegistrySetting = True End Function
使用这样的宏可将HKEY_CURRENT_USER \ Software \ Microsoft \ Office8.0 \ Excel \ Microsoft Excel中的新值保存为键DefaultPath:
MyStringVar = "HKEY_CURRENT_USER\Software\Microsoft\Office.0\Excel\Microsoft Excel" MyBooleanVar = SetRegistrySetting(MyStringVar, _ "DefaultPath", "C:\FolderName")
从注册表中读取信息通过下面的宏,您可以从注册表中读取信息:
Function GetRegistrySetting(Section As String, Key As String) As String Dim wd As Word.Application GetRegistrySetting = "" Set wd = New Word.Application ' create the Word application object On Error Resume Next GetRegistrySetting = wd.System.PrivateProfileString("", Section, Key) On Error GoTo 0 Set wd = Nothing ' destroy the Word application object End Function
使用这样的宏可以从键DefaultPath
中读取值。从HKEY_CURRENT_USER \ Software \ Microsoft \ Office8.0 \ Excel \ Microsoft Excel中:
MyStringVar = "HKEY_CURRENT_USER\Software\Microsoft\Office.0\Excel\Microsoft Excel" MyStringVar = SetRegistrySetting(MyStringVar, _ "DefaultPath")