How to read a file and write into a text file? - file-io

I want to open mis file, copy all the data and write into a text file.
My mis file.
File name – 1.mis
M3;3395;44;0;1;;20090404;094144;8193;3;0;;;;
M3;3397;155;0;2;;20090404;105941;8193;3;0;;;;
M3;3396;160;0;1;;20090404;100825;8193;3;0;;;;
M3;3398;168;0;2;;20090404;110106;8193;3;0;;;;
so on...,
The above data should appear in a text file with same file name (1.txt).
I tried this code.
Dim sFileText As String
Dim iFileNo As Integer
iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
Input #iFileNo, sFileText
Loop
Close #iFileNo
Open "C:\Clients\Converter\2.txt" For Output As #iFileNo
Do While Not EOF(iFileNo)
Write #iFileNo, sFileText
Loop
Close #iFileNo
Nothing is saved in 1.txt.

It far easier to use the scripting runtime which is installed by default on Windows
Just go project Reference and check Microsoft Scripting Runtime and click OK.
Then you can use this code which is way better than the default file commands
Dim FSO As FileSystemObject
Dim TS As TextStream
Dim TempS As String
Dim Final As String
Set FSO = New FileSystemObject
Set TS = FSO.OpenTextFile("C:\Clients\Converter\Clockings.mis", ForReading)
'Use this for reading everything in one shot
Final = TS.ReadAll
'OR use this if you need to process each line
Do Until TS.AtEndOfStream
TempS = TS.ReadLine
Final = Final & TempS & vbCrLf
Loop
TS.Close
Set TS = FSO.OpenTextFile("C:\Clients\Converter\2.txt", ForWriting, True)
TS.Write Final
TS.Close
Set TS = Nothing
Set FSO = Nothing
As for what is wrong with your original code here you are reading each line of the text file.
Input #iFileNo, sFileText
Then here you write it out
Write #iFileNo, sFileText
sFileText is a string variable so what is happening is that each time you read, you just replace the content of sFileText with the content of the line you just read.
So when you go to write it out, all you are writing is the last line you read, which is probably a blank line.
Dim sFileText As String
Dim sFinal as String
Dim iFileNo As Integer
iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
Input #iFileNo, sFileText
sFinal = sFinal & sFileText & vbCRLF
Loop
Close #iFileNo
iFileNo = FreeFile 'Don't assume the last file number is free to use
Open "C:\Clients\Converter\2.txt" For Output As #iFileNo
Write #iFileNo, sFinal
Close #iFileNo
Note you don't need to do a loop to write. sFinal contains the complete text of the File ready to be written at one shot. Note that input reads a LINE at a time so each line appended to sFinal needs to have a CR and LF appended at the end to be written out correctly on a MS Windows system. Other operating system may just need a LF (Chr$(10)).
If you need to process the incoming data then you need to do something like this.
Dim sFileText As String
Dim sFinal as String
Dim vTemp as Variant
Dim iFileNo As Integer
Dim C as Collection
Dim R as Collection
Dim I as Long
Set C = New Collection
Set R = New Collection
iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
Input #iFileNo, sFileText
C.Add sFileText
Loop
Close #iFileNo
For Each vTemp in C
Process vTemp
Next sTemp
iFileNo = FreeFile
Open "C:\Clients\Converter\2.txt" For Output As #iFileNo
For Each vTemp in R
Write #iFileNo, vTemp & vbCRLF
Next sTemp
Close #iFileNo

If you want to do it line by line:
Dim sFileText As String
Dim iInputFile As Integer, iOutputFile as integer
iInputFile = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iInputFile
iOutputFile = FreeFile
Open "C:\Clients\Converter\2.txt" For Output As #iOutputFile
Do While Not EOF(iInputFile)
Line Input #iInputFile , sFileText
' sFileTextis a single line of the original file
' you can append anything to it before writing to the other file
Print #iOutputFile, sFileText
Loop
Close #iInputFile
Close #iOutputFile

FileCopy "1.mis", "1.txt"

An example of reading a file:
Dim sFileText as String
Dim iFileNo as Integer
iFileNo = FreeFile
'open the file for reading
Open "C:\Test.txt" For Input As #iFileNo
'change this filename to an existing file! (or run the example below first)
'read the file until we reach the end
Do While Not EOF(iFileNo)
Input #iFileNo, sFileText
'show the text (you will probably want to replace this line as appropriate to your program!)
MsgBox sFileText
Loop
'close the file (if you dont do this, you wont be able to open it again!)
Close #iFileNo
(note: an alternative to Input # is Line Input # , which reads whole lines).
An example of writing a file:
Dim sFileText as String
Dim iFileNo as Integer
iFileNo = FreeFile
'open the file for writing
Open "C:\Test.txt" For Output As #iFileNo
'please note, if this file already exists it will be overwritten!
'write some example text to the file
Print #iFileNo, "first line of text"
Print #iFileNo, " second line of text"
Print #iFileNo, "" 'blank line
Print #iFileNo, "some more text!"
'close the file (if you dont do this, you wont be able to open it again!)
Close #iFileNo
From Here

Related

How to read all information from shell command in VBA and save it in .txt file

I try to use this code:
Shell(nppPath & " " & fileToOpen, vbNormalFocus)
which opens txt file nppPath = "C:\Windows\notepad.exe" but I cannot read from it and save it as .txt file using VBA.
Looking forward to any suggestions.
I'm presuming you copied the nppPath over wrong as it should be
nppPath = "C:\Windows\System32\notepad.exe"
but for reading from the text file you could use free file:
Dim IntFile As Integer, StrFileName As String, StrFileContent As String
StrFileName = fileToOpen 'Your file location here
IntFile = FreeFile
Open StrFileName For Input As #IntFile
StrFileContent = Input(LOF(IntFile), IntFile) 'This now contains the text
Close #IntFile
This will read the text file into a single variable that you can then use however you wish.
If you want to write to a text file you can use the following code:
Dim StrNewLocation As String, StrFileContent As String
StrNewLocation = "" 'Put the new files name and location here
StrFileContent = "Example" 'The text to go into the new file
Open StrNewLocation For Output As #1
Write #1, StrFileContent
Close #1
Hopefully this helps you solve your problem if not send me a message and I'll see what I can do.

How to remove the empty line that excel makes when creating a csv file using vba

As some of you probably know, excel creates an empty line at the end of CSV files. I'm looking for a solution that can remove/delete this line because I want to upload the CSV file to a different program, which can't handle this empty line.
First I thought it was the way I created the CSV file, but after spending hours searching for a solution, I found out that it's a bug.
Does anybody have a solution to this problem, removing the last line in a CSV file using VBA?
Try calling this Sub to kill the last line of the csv-file. You have to insert the path into the code:
Sub KillLastLine()
Dim fso As New FileSystemObject
Dim ts As TextStream
Dim filecontent As String
Dim myFile As File
Set myFile = fso.GetFile("YourCSVPathHere")
Set ts = myFile.OpenAsTextStream(ForReading)
While Not ts.AtEndOfStream
filecontent = filecontent & ts.ReadLine & vbCrLf
Wend
Set ts = myFile.OpenAsTextStream(ForWriting)
ts.Write Left(filecontent, Len(filecontent) - 1)
ts.Close
End Sub
Sub ZUtil_TextFile_FindReplace(FilePath As String, strOld As String, strNew As String)
'PURPOSE: Modify Contents of a text file using Find/Replace
'SOURCE: www.TheSpreadsheetGuru.com
Dim TextFile As Integer
Dim FileContent As String
'Determine the next file number available for use by the FileOpen function
TextFile = FreeFile
'Open the text file in a Read State
Open FilePath For Input As TextFile
'Store file content inside a variable
FileContent = Input(LOF(TextFile), TextFile)
'Clost Text File
Close TextFile
'Find/Replace
FileContent = Replace(FileContent, strOld, strNew)
FileContent = Replace(FileContent, "^(?:[\t ]*(?:\r?\n|\r))+", "")
If Right(FileContent, 2) = Chr(13) & Chr(10) Then
FileContent = Left(FileContent, Len(FileContent) - 2)
End If
'Determine the next file number available for use by the FileOpen function
TextFile = FreeFile
'Open the text file in a Write State
Open FilePath For Output As TextFile
'Write New Text data to file
Print #TextFile, FileContent
'Close Text File
Close TextFile
'MsgBox "ZUtil_TextFile_FindReplace TERMINADO"
End Sub

Get full content from current word document

I have a MS-Word .docm document with a macro inside. In this macro I want to get the full content from the document as a byte array. The content should contain the full information of the document and when I save this content I should be able to open this file in Word again.
Im totally new to vba and don't have any idea where to start. I thought about saving the document in a temp folder to read this file to get the content but maybe there is a better way.
I suggest you to use
ThisDocument.SaveAs "c:\temp\mydoc.docm"
Then simply use that file for your further operation.
Or to print out your file as bytes:
Sub SaveAsByteArray()
Dim thisFile As String
thisFile = ActiveDocument.FullName
Dim targetFile As String
targetFile = "C:\temp\doc.docm"
Dim sourceFileNum As Integer
Dim targetFileNum As Integer
Dim aByte As Byte
sourceFileNum = FreeFile
Open thisFile For Random Access Read As sourceFileNum Len = 1
targetFileNum = FreeFile
Open targetFile For Random Access Write As targetFileNum Len = 1
Do While Not EOF(sourceFileNum)
Get #sourceFileNum, , aByte
Put #targetFileNum, , aByte
Loop
Close sourceFileNum
Close targetFileNum
End Sub
But this sub adds an extra byte at the end, so Excel will open a dialog asking if you want to fix the contents. If you choose yes, then word is able to open the file.
Or put it into an array:
Sub SaveAsByteArray()
Dim thisFile As String
thisFile = ActiveDocument.FullName
Dim sourceFileNum As Integer
Dim arr()
Dim arr_n as long
arr_n = 0
Dim aByte As Byte
sourceFileNum = FreeFile
Open thisFile For Random Access Read As sourceFileNum Len = 1
Do While Not EOF(sourceFileNum)
Get #sourceFileNum, , aByte
ReDim Preserve arr(0 to arr_n)
arr(arr_n) = aByte
arr_n=arr_n+1
Loop
Close sourceFileNum
End Sub

How to read a big file list from a textfile to form a query

I have this query which I have to run multiple times in excel and i need to change the filelists in it.
select * from files
where
filename in ('filename1','filename2')
so I have a TEMP in my query filename in TEMP and I want to loop and get the result for all filelists. My onlyproblem is reading .txt into the TEMP and executing the query once for all filenames in the txt file. i know how to read files line by line so that didn't help.
my text files which I want to read the lists from are like
filename1
filename2
.
.
.
.
filename15000
yes some big numbers.
dim filelist as string
dim filelistpath as string
sqlstring = "select count(*) from files where filename in TEMP"
filelistpath = "c:\"
open filelistpath for input as #1
do while not EOF(1)
line input #1,text
'here i should construct my file list to replace the TEMP below, how ?
loop
close #1
sqlstring = replace(sqlstring,TEMP, filelist)
set rs = conn.execute(sqlstring)
'here i want to write the result to my excel sheet, how ?
thanks
I formatted the text and just read it like that as a whole
Function GetText(sFile As String) As String
Dim nSourceFile As Integer, sText As String
''Close any open text files
Close
''Get the number of the next free text file
nSourceFile = FreeFile
''Write the entire file to sText
Open sFile For Input As #nSourceFile
sText = Input$(LOF(1), 1)
Close
GetText = sText
End Function

Excel 2007 VBA Macro reading a text file line by line how do I stop delimiting on a comma (,)

I have a simple Excel 2007 Macro that is reading a text file line by line and displaying the output.
This macro is breaking on commas. I want it to simply read the entire line breaking on a carrage return.
What am I doing wrong?
Sub Directory()
Dim strFileName As String
Dim strDirectory As String
Dim intFileKey As Integer
Dim strLine As String
strDirectory = "C:\Documents and Settings\e1009028\My Documents\embosstest"
ChDir (strDirectory)
strFileName = Dir("*.txt")
Do While Len(strFileName) > 0
intFileKey = FreeFile
Open strFileName For Input As intFileKey
Do While Not EOF(intFileKey)
Input #intFileKey, strLine
MsgBox Mid(strLine, 1, 10)
Loop
strFileName = Dir
Loop
End Sub
Here is a sample text file:
1 blahblahblabh
2 blah,blahblah
For a quick fix, try using Line input instead of input.
For a more modern solution, have a look at FileSystemObject, especially OpenTextFile.