PDA

View Full Version : Cannot read from the .ini file



Nuz
10-27-2011, 02:00 AM
I try to read settings from the .ini configuration-file with VBA. For some reason I always get an empty string and in some cases VBA throws a Type mismatch-error.

When I have this VBA code:
iNumber = System.PrivateProfileString(sFileName, "Sec1", "Value1")
...I get a Type mismatch error. iNumber variable is declared as Integer.

When I try this:
sString = System.PrivateProfileString(sFileName, "Sec2", "Value1")
...I get an empty string. sString variable is declared as String.

The .ini-file where I try to read looks like this:
[Sec1]
Value1=12345
[Sec2]
Value1=Company ABC
Any idea what goes wrong with this?

Tommy
10-28-2011, 06:49 AM
System.PrivateProfileString returns a string so when you do


iNumber = System.PrivateProfileString(sFileName, "Sec1", "Value1")


it will complain because iNumber is an Integer, to make it an integer do


iNumber = cint(val(System.PrivateProfileString(sFileName, "Sec1", "Value1)") )


I recreated you sample and didn't get an empty string.

Nuz
10-28-2011, 07:11 AM
Thanks. I actually had a wrongly specified path in the variable sFilename. It works now perfectly.

Frosty
10-28-2011, 10:53 AM
Using CInt on an empty string will give an error.

Tommy
10-28-2011, 11:53 AM
I didn't do CInt on an empty string. I did CInt(Val("")) which is 0.

Sub a()
MsgBox CInt(Val(""))
End Sub

Frosty
10-28-2011, 02:04 PM
Sure enough, you didn't. My eye passed over the boring black Val function and simply saw the pretty blue CInt :)

Not a heavy user of the Val function, although I think reading items from ini files should always be passed into string variables, rather than using conversion functions to immediately pass into other variable types (since error trapping becomes so difficult...

But that's a longer explanation for a simple question/answer... type the right filepath ;)

Sorry to confuse the issue.

Tommy
10-28-2011, 02:15 PM
VBA is so forgiving that the CInt(Val()) is not necessary. I was focused on the type mismatch, I didn't put the code in the IDE for syntax checking so I though I had goofed. :) I have been known to do that on occasion. So no confusion I just though I had a bad case of fat fingers.