Text file
I am new here and I want t know how to change the value of a number in a text file.
This is for a project I am working on for the company I work for.
The number is used to create new project numbers by clicking a single button.
With the code in the file below I can read the text from the file on my desktop and put it in a cell in Excel. But after that I want the number to increase by 10.
Can somebody please help me.
Thanks alot in advance.
Sub Hallo()
Dim X As Double
Dim TXT As String
Open "C:\Users\Leon\Desktop\Project nummer.txt" For Input As #1
Do While Not EOF(1)
Line Input #1, TXT
Sheets("Blad1").Range("C2") = TXT
Loop
Close #1
End Sub
Write back to the file
Option Explicit
Sub Hallo()
Const FOLDER = "C:\Users\Leon\Desktop\"
Const FILENAME = "Project nummer.txt"
Const INC = 10
Dim s As String, ff
ff = FreeFile()
Open FOLDER & FILENAME For Input As #ff
Line Input #ff, s
Close #ff
If IsNumeric(s) Then
Sheets("Blad1").Range("C2") = Format(s, 0)
' save new number
ff = FreeFile()
Open FOLDER & FILENAME For Output As #ff
Write #ff, Val(s) + INC
Close #ff
Else
MsgBox s & " not valid number", vbCritical
End If
End Sub
Related
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.
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 need to export data from Excel to a comma delimited file. I am using a button that runs a macro that creates the text file in a location I specify and exports values.
But, I want to copy this Excel with the same macro, and add different values. When I run the macro in the copied Excel file I want the same text delimited file to add these values under the previous set of values, not overwrite the values from the first Excel file.
How is this possible? I want to use the same text file each time.
Append using following routine:
Sub writeCSV(ByVal thisRange As Range, ByVal filePath As String, _
Optional ByVal fileAppend As Boolean = False)
Dim cLoop As Long, rLoop As Long
Dim ff As Long, strRow As String
ff = FreeFile
If fileAppend Then
Open filePath For Append As #ff
Else
Open filePath For Output As #ff
End If
For rLoop = 1 To thisRange.Rows.Count
strRow = ""
For cLoop = 1 To thisRange.Columns.Count
If cLoop > 1 Then strRow = strRow & ","
strRow = strRow & thisRange.Cells(rLoop, cLoop).Value
Next 'cLoop
Print #ff, strRow
Next 'rLoop
Close #ff
End Sub
Example usage
writeCSV sheet1, "c:\test.txt", true
It is easy to do it by using a StreamWriter. The AppendText function of the FileInfo class returns one that is configured for appending text to an existing file.
I write my example as pseudo code, as I don't know how you are retrieving the information from Excel. The File handling part, however, is complete:
Dim file As New FileInfo("C:\myOuputFile.csv")
Using writer = file.AppendText()
While isRowAvailable
writer.WriteLine("Write next row")
End While
End Using
The Using statement automatically closes the file at the end.
I am trying to achieve a simple objective,insert row count and column count summary of an excel file to an existing notepad.
I have multiple files in a folder and would like to run this operation for each file and send the details to a notepad.
Issue: Every time i run the code it deletes existing content and inserts new data into the notepad. I would like to retain existing data and start appending from a new line
code:
Sub Sndtotxt()
Dim FF
Dim rCnt AS INTEGER
Dim cCnt AS INTEGER
rCnt = ActiveSheet.UsedRange.Rows.Count
cCnt = ActiveSheet.UsedRange.Columns.Count
FF = FreeFile()
OPEN "C:\Temp files\summaryreport.txt" FOR Output AS #FF
Print #FF, rCnt
Print #FF, cCnt
CLOSE #FF
END Sub
replace
OPEN "C:\Temp files\summaryreport.txt" FOR Output AS #FF
with
OPEN "C:\Temp files\summaryreport.txt" FOR Append AS #FF
In terms of looping through files in a folder, suggest you start with my code from Loop through files in a folder using VBA?
Change the path below for both
Excel files C:\temp\
Txt report C:\Temp\test.txt
to suit
Sub GetEm()
Dim WB As Workbook
Dim StrFile As String
Dim FF
FF = FreeFile()
Open "C:\Temp\test.txt" For Append As #FF
StrFile = Dir("c:\temp\*.xls*")
Do While Len(StrFile) > 0
Set WB = Workbooks.Open("c:\temp\" & StrFile)
StrFile = Dir
Print #FF, WB.Name, WB.Sheets(1).UsedRange.Rows.Count, WB.Sheets(1).UsedRange.Columns.Count
WB.Close
Loop
Close #FF
End Sub
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