Public Function MakeTxtFile(SourceFile As String, TargetFile As String)
'This function reads the contents of the SourceFile that contains the invalid underscore characters
'in the data items. replaces them with commas and writes the amended line to the TargetFile.
'
'The next step is to use the TargetFile as the new sourceFile to import into the prestructured Access table.
'
'Note the target file does not need to know the field headings as they have already been established via the table accepting the data.
'Check to se if the source file exists before doing anything
If Dir(SourceFile) = "" Then
MsgBox "Cannot find " & SourceFile & ". Import rountine abandoned", vbExclamation + vbOKOnly, "Procedure Failed"
Exit Function
End If
'if the target file already exists then ask the user if they want to overwrite it
If Dir(TargetFile) <> "" Then
If MsgBox(tartgetfile & " already exists. Do you want to overwrite it?", vbQuestion + vbYesNo, "File already exists") = vbYes Then
Kill TargetFile
DoEvents
Else
MsgBox "Import cancelled by user", vbInformation + vbOKOnly, "Information"
Exit Function
End If
End If
Dim strLine As String
Dim nIndex As Integer
nIndex = 0
Open SourceFile For Input As #1
Open TargetFile For Output As #2
Do While Not EOF(1)
Line Input #1, strLine 'read the incoming line from the SourceFile
If nIndex > 0 Then 'Do not do anything with the first line - this contains the column headings
Print #2, Replace(strLine, "_", ",") 'Replace all underscores with commas to act as delimiters and write to the TartgetFile
End If
nIndex = nIndex + 1 'Prevent from skipping the next line of data
Loop
Close #1
Close #2
Debug.Print "Done"
End Function