Hack 67 Store Settings and Data in .ini Files![]() ![]() information using plain-text files that are easy to create, easy to edit, and easy to remove.Before Windows 95 came along with the Windows registry for storing system information, Windows used .ini filestext files used to store program-specific data. Many programs, and even Windows, still use these files to store certain information. A search on your hard drive for *.ini files will likely turn up dozens or even hundreds of entries.These files are very useful for storing data after a macro finishes running in VBA, or for things like numbering documents sequentially [Hack #77] and creating an improved MRU [Hack #13] after Word closes.The .ini, or Config, files have a simple structure. Each file is divided into one or more sections, and each section contains sets of key/value pairs. The contents of a Config file look like the following: [MRU_Files]Each section name is on its own line and surrounded by brackets. Each line within the section contains a key/value pair separated by an equals sign (=).VBA includes a feature called the PrivateProfileString property, which you can use from any macro, to read and write these files. When you read from or write to a Config file, you need three values: the filename, the section name, and the key name. If you're writing to the file, you also need the value to assign to the key.To store the name of the current document in a Config file under the key CurrDoc in the section WordInfo in a file named WordSettings.ini, you'd use the following syntax: System.PrivateProfileString("WordSettings.ini", "WordInfo", "CurrDoc") = _If no file named WordSettings.ini exists, the macro creates one. If the file does exist, it replaces any value already associated with the key CurrDoc in the section WordInfo.To retrieve this same information from the Config file, use the following syntax: strSetting = System.PrivateProfileString("WordSettings.ini", _If the file, section, or key doesn't exist, it returns an empty string.The following example shows you how to use a Config file from within a macro. These two AutoMacros [Hack #60], when placed in your Normal template, will record the name of the active document when you quit Word and then open that document the next time you start Word: Sub AutoExecBecause Config files are just plain-text files, they can be viewed and edited using any standard text editor, such as Notepad. |