View Single Post
  #2  
Old 29-01-2006, 00:13
Alex's Avatar
Alex Alex is offline
Administrator
 
Join Date: Nov 2002
Posts: 1,932
Blog Entries: 4
Default

Shelby,

I personally prefer the native VBA file functions simply because it is not dependent on the presence of the FileSystemObject library on the target machine.

Here is how you open a file and write some text to it:

Code:
Open "C:\File.txt" For Output As #1
Print #1, "Some text for line1"
Print #1, "Some text for line2"
Close #1
Here is how you read the text file line by line:

Code:
Dim sLine As String
Open "C:\File.txt" For Input As #1
While Not EOF(1)
    Line Input #1, sLine
    ' Do something with the read line
Wend
Close #1
Seems pretty simple and it works without any external components.

I also frequently use Windows API to read settings from INI files. This way I don't have to write any text parsers or anything to extract the data from the INI files myself. Here are the functions I use for this:

Code:
Private Declare Function GetPrivateProfileString Lib "kernel32" _
                Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, _
                ByVal lpKeyName As Any, ByVal lpDefault As String, _
                ByVal lpReturnedString As String, ByVal nSize As Long, _
                ByVal lpFileName As String) As Long
Private Declare Function WritePrivateProfileString Lib "kernel32" _
                Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, _
                ByVal lpKeyName As Any, ByVal lpString As Any, _
                ByVal lpFileName As String) As Long

Public Function GetConfigData(ByVal strSection As String, ByVal strKey As String, ByVal strDefValue As String, ByVal strINIFile As String) As String
    Dim n As Long
    Dim strVal As String
    strVal = Space$(260)
    n = GetPrivateProfileString(strSection, strKey, strDefValue, strVal, Len(strVal), strINIFile)
    GetConfigData = Left$(strVal, n)
End Function

Public Sub SetConfigData(ByVal strSection As String, ByVal strKey As String, ByVal strValue As String, ByVal strINIFile As String)
    WritePrivateProfileString strSection, strKey, strValue, strINIFile
End Sub
Reply With Quote