I have the following macro that is should write new data onto a new line in a text/csv file, however it overwriting the existing text in the file, I thought that write wrote to a new line as opposed to print. I am not sure what I am doing wrong
Sub picking()
Range("d14").NumberFormat = "mm/dd/yyyy"
Range("d14").Value = Now
Range("e14").NumberFormat = "hh:mm"
Range("e14").Value = Now
Range("e17").Value = "Picking"
Call outputcsv
End Sub
Sub outputcsv()
Dim Fullpath As String
Dim outputstring As String
Fullpath = Worksheets("Maintence").Range("c5")
Open Fullpath For Output As #1
outputstring = Worksheets("CSV").Range("A1")
Write #1, outputstring
Close #1
End Sub
You just need to change...
Open Fullpath For Output As #1
...to...
Open Fullpath For Append As #1
Note that "Output" changes to "Append."
Also note that "Append" will create the file - just as Output does - if it doesn't already exist. No need to pre-create it.
Related
I need help in modifying the CSV file using VBA. I did research and came up with this solution. However, I can't get the expected output. So, for example, I have a CSV file:
ProductID,ProductName,SupplierName,CategoryID,Unit,Price
,,,,,
1,Chais,John Ray,1,10 boxes x 20 bags,18.00093483
2,Chang,Michael,1,24 - 12 oz bottles,19.66890343
I want to change all the values under the productname and suppliername. And change something like the combination of ProductID and the Column Name. My expected output should look like:
ProductID,ProductName,SupplierName,CategoryID,Unit,Price
,,,,,
1,1 ProductName,1 SupplierName,1,10 boxes x 20 bags,18.00093483
2,2 ProductName,2 SupplierName,1,24 - 12 oz bottles,19.66890343
It can occur multiple times and can change the column location. This is my code:
Sub test()
Dim FilePath As String, LineFromFile As Variant, LineItems() As String, strFile As Variant
FilePath = "C:\Users\mestrivo\Documents\Files\MyFirstProg\test.csv"
Open FilePath For Input As #1
Do Until EOF(1)
Line Input #1, LineFromFile
LinteItems = Split(LineFromFile, ",")
LineItems(1) = LineItems(0) & " ProductName"
LineItems(2) = LineItems(0) & " SupplierName"
strFile = Join(LineItems, ",")
Loop
Open "C:\Users\mestrivo\Documents\Files\MyFirstProg\test - 2.csv" For Output As #1
Print #1, strFile
Close #1
End Sub
Please help me check my code. I got an error on this part:
Open "C:\Users\mestrivo\Documents\Files\MyFirstProg\test - 2.csv" For Output As #1
it says that the file is already open.
NEVER hard-code file handles, they aren't for you to grab, they're for VBA to query what's available and give you a free, usable file handle. Use the FreeFile function to do this.
Dim fileHandle As Long
fileHandle = FreeFile
Then replace all hard-coded #1 handles with #fileHandle.
You cannot open two different files using the same handle. You've already opened the file for input:
Open FilePath For Input As #1
So when you try to use the same handle for output...
Open "C:\Users\mestrivo\Documents\Files\MyFirstProg\test - 2.csv" For Output As #1
That's when you get an error; you haven't closed the #1 handle yet, and now you're trying to reuse it to open another file - you can't do that.
You're dealing with two files, so either you open the first one, read it, then close it before you open the second one, write to it and then close it - or, you open both, and write to one as you read the other, then close both.
Either way, you shouldn't hard-code file handles. Use FreeFile to get a free file handle. Always.
Try this:
Sub test()
Dim FilePath As String, LineFromFile As Variant, _
LineItems() As String, strFile As Variant
FilePath = "mycsv.csv"
Open FilePath For Input As #1
Do Until EOF(1)
Line Input #1, LineFromFile
LineItems() = Split(LineFromFile, ",")
'I suggest to add the following 'If' statements
If LineItems(0) <> "" Then
LineItems(1) = LineItems(0) & " ProductName"
LineItems(2) = LineItems(0) & " SupplierName"
End If
If strFile <> "" Then strFile = strFile & Chr(10)
'-------------------------------------------------
strFile = strFile & Join(LineItems, ",")
Loop
'In the next 'Open' statement you are trying to
'assign an object over another that's already opened,
'therefore you must close the previous object first
'and / or declare the second one with another name
Close #1
Open "mycsv2.csv" For Output As #1
Print #1, strFile
Close #1
End Sub
I would like to ask the community if there is anyway someone can store file directories path into a notepad or other word document and let VBA scan through each file directories and check if file exist.
Here's a commented code that uses dir to illustrate the comment above.
'This function will check if the file or the directory
'exists and returns a boolean.
Function ExistTest(Path As String) As Boolean
'The function default return is set to false
ExistTest = False
'Remove stream reader appending
Path = Replace(Path, "", "")
'Dir returns a 0-length string if the file or directory doesn't exist
If Len(Dir(Path)) > 0 Or Len(Dir(Path, vbDirectory)) > 0 Then
ExistTest = True
End If
End Function
Sub main()
'Defining the source file
Dim SourceFile As String: SourceFile = "d:/t.txt"
'Open a stream reader
Open SourceFile For Input As #1
'Read all line until the end of file
'Before we define a temporary string the path as we go through
'the sourcefile
Dim TempPath As String
Do Until EOF(1)
Line Input #1, TempPath
'Debug print the results
Debug.Print (TempPath & " " & ExistTest(TempPath))
Loop
Close #1
End Sub
Debug.Print will print in the immediate window. To enable that, go to View > Immediate Window
I'm reading multiple csv files into excel for some number crunching. The file reads appear to work with each excel column having the csv file name inserted for confirmation. Odd thing. Each csv file name is correctly inserted into the sheet, but the data is all the same as the first file.
Is there a way to flush / reset ..... something, so the next read file data actually is the next file?
Excel VBA code snippet:
Public Const sRawFilePath As String = "\\server1\Sample.RAW.Files\"
----------------
Sub ImportCSV()
Dim sFullFilePath, sFile As String
fFIle = FreeFile()
sFile = Dir(sRawFilePath & "*.csv")
sFullFilePath = sRawFilePath & sFile
While sFile <> ""
Open sFullFilePath For Input As fFIle
While Not EOF(fFIle)
Line Input #fFIle, sLine
""
"take the sLine string and separate the comma delimited values for insertion into columns "
"This part works fine"
""
Wend
Close fFIle
sFile = Dir()
Wend
End Sub
Stepping through the code I can confirm the next file is in the queue, but the read data is not representing the next file, just the first file, ... and always the first file even though 20 more files are read.
PS - This forum has been an amazing resource.
The problem is you define sFullFilePath which locks in the file that you're opening. So even though you're successfully looping through the files with Dir, you will only open the first one because you locked it in. Don't use that variable at all:
'Change this line
Open sFullFilePath For Input As fFIle
'To be this instead
Open sRawFilePath & sFile For Input As fFIle
Rather than executing Dir(sRawFilePath & "*.csv") in every call, you should just execute Dir in subsequent calls. The error causes you to re-read the first file again and again.
I'm trying to parse a text document using VBA and return the path given in the text file. For example, the text file would look like:
*Blah blah instructions
*Blah blah instructions on line 2
G:\\Folder\...\data.xls
D:\\AnotherFolder\...\moredata.xls
I want the VBA to load 1 line at a time, and if it starts with a * then move to the next line (similar to that line being commented). For the lines with a file path, I want to write that path to cell, say A2 for the first path, B2 for the next, etc.
The main things I was hoping to have answered were:
What is the best/simple way to read through a text file using VBA?
How can I do that line by line?
for the most basic read of a text file, use open
example:
Dim FileNum As Integer
Dim DataLine As String
FileNum = FreeFile()
Open "Filename" For Input As #FileNum
While Not EOF(FileNum)
Line Input #FileNum, DataLine ' read in data 1 line at a time
' decide what to do with dataline,
' depending on what processing you need to do for each case
Wend
#Author note - Please stop adding in close #FileNum - it's addressed in the comments, and it's not needed as an improvement to this answer
I find the FileSystemObject with a TxtStream the easiest way to read files
Dim fso As FileSystemObject: Set fso = New FileSystemObject
Set txtStream = fso.OpenTextFile(filePath, ForReading, False)
Then with this txtStream object you have all sorts of tools which intellisense picks up (unlike using the FreeFile() method) so there is less guesswork. Plus you don' have to assign a FreeFile and hope it is actually still free since when you assigned it.
You can read a file like:
Do While Not txtStream.AtEndOfStream
txtStream.ReadLine
Loop
txtStream.Close
NOTE: This requires a reference to Microsoft Scripting Runtime.
For completeness; working with the data loaded into memory;
dim hf As integer: hf = freefile
dim lines() as string, i as long
open "c:\bla\bla.bla" for input as #hf
lines = Split(input$(LOF(hf), #hf), vbnewline)
close #hf
for i = 0 to ubound(lines)
debug.? "Line"; i; "="; lines(i)
next
You Can use this code to read line by line in text file and You could also check about the first character is "*" then you can leave that..
Public Sub Test()
Dim ReadData as String
Open "C:\satheesh\myfile\file.txt" For Input As #1
Do Until EOF(1)
Line Input #1, ReadData 'Adding Line to read the whole line, not only first 128 positions
If Not Left(ReadData, 1) = "*" then
'' you can write the variable ReadData into the database or file
End If
Loop
Close #1
End Sub
The below is my code from reading text file to excel file.
Sub openteatfile()
Dim i As Long, j As Long
Dim filepath As String
filepath = "C:\Users\TarunReddyNuthula\Desktop\sample.ctxt"
ThisWorkbook.Worksheets("Sheet4").Range("Al:L20").ClearContents
Open filepath For Input As #1
i = l
Do Until EOF(1)
Line Input #1, linefromfile
lineitems = Split(linefromfile, "|")
For j = LBound(lineitems) To UBound(lineitems)
ThisWorkbook.Worksheets("Sheet4").Cells(i, j + 1).value = lineitems(j)
Next j
i = i + 1
Loop
Close #1
End Sub
I'm trying to write a file using VBA. My code is below. It worked the first time, but when i closed the excel file (.xlsm) and try to use it again, it doesn't work.
I do not get any errors when running the macro but the new file does not appear
Sub LogInformation(LogMessage As String)
Const LogFileName As String = "TEXTFILE.db"
Dim FileNum As Integer
FileNum = FreeFile ' next file number
Open LogFileName For Append As #FileNum ' creates the file if it doesn't exist
Print #FileNum, LogMessage ' write information at the end of the text file
Close #FileNum ' close the file
End Sub
Sorry guys. That was dumb.
The default relative path is in User/%MyUser%/Documents.
I need to use ChDir then open/write/close the file.
Chdir(ActiveWorkbook.Path)