Tested in Excel 365 (16.8730.2046) 64-bit
When you need to have certain parameters established without asking the user every time you run a macro, you can create a file containing all these parameters and read it at runtime. A good example is when you need to fill in the name and email of the person generating the report. Or when you call external apps and you need to instruct VBA to wait a certain amount of time, allowing user to modify the wait period.
Here is the code and below you’ll find a config file example.
Code:
- Public Const ConfigPathAndName = "C:\TEMP\ConfigSample.txt"
- Public Const ConfigDelimiter = ":"
- Public Const ConfigComment = "'"
- '
- Function GetConfigSettings() As Dictionary
- ' needs reference to Microsoft Scripting Runtime
- Dim f
- Dim strFile, tempArray
- Dim dSettings As New Dictionary
- f = FreeFile
- strFile = ""
- Open ConfigPathAndName For Input As #f
- ' parse the file
- Do Until EOF(f)
- Line Input #f, strFile
- If Left(strFile, 1) <> ConfigComment Then
- tempArray = Split(strFile, ConfigDelimiter)
- ' add to dictionary
- If Not dSettings.Exists(tempArray(1)) Then _
- dSettings.Add tempArray(0), Trim(tempArray(1))
- End If
- Loop
- Close #f
- Set GetConfigSettings = dSettings
- ' discard the dictionary
- Set dSettings = Nothing
- End Function
- '
- Sub main()
- Dim MySettings As New Dictionary
- Set MySettings = GetConfigSettings
- For Each dkey In MySettings
- Debug.Print dkey, MySettings.Item(dkey)
- Next
- Set MySettings = Nothing
- End Sub
Note: Always discard a dictionary after use. They tend to slow down Excel if they stay in the memory.
More about dictionaries here.
Config: