I’ve trying to simplify a script and it’s routines and I’m not quite sure what’s the best way of doing it. I want to repeat code as little as possible. So below is my current code.
This is the Filename function that basically checks if an ini-file exists.
It should probably just run once. The way it’s now, it’s run everytime the string “FileName” is used, which is a lot.
Function FileName()
FileName = "C:\Apps\Templates\fields.ini"
''# Does ini-file exist?
If Len(Dir$(FileName)) = 0 Then
MsgBox ("Can't find the file " & FileName & ".")
End If
End Function
Then I have this regPath and regString function which basically just picks up the path in the registry that the script should read from.
Public Function regPath()
regPath = ReadIni(FileName, "Registry", "Path")
End Function
Public Function regString()
regString = ReadIni(FileName, "Registry", "String")
End Function
Then there’s the first function that reads the actual registry for its value.
Public Function regFirstname()
regStrFistname = ReadIni(FileName, "Fields", "Firstname")
Set objShell = CreateObject("Wscript.Shell")
Dim value As String
value = objShell.RegRead(regPath & "\" & regStrfirstname)
regFornavn = value
End Function
I have loads of this last one, just that it reads other parts of the registry. All this code is contained in a module in a Word 2007 template.
And from my Document_New() sub I just basically want to pick up the value from the registry, without having so much code in the Document_New() sub routine. This way I can use the values in forms and other areas as well.
How should I structure this? Any reply would be appreciated.
You can probably change the Filename function to a sub:
Add a variable to the top of your module called gvFilename. Note that these variables are reset if an unhandled error occurs, so you may need to run the sub again if gvFilename contains a null string (vbNullString).
These:
Can probably be changed to:
Which can be called like so:
The registry reader can also probable be changed like so:
As an aside, avoid using reserved words like Value in your code, it can lead to untold grief.