Delete line after reading from text file - text

How do I get this script to delete each line of text after reading it instead of just going onto the next one and still leaving it in the text file.
What can I do to change it?
Dim fso
Set objEmail = CreateObject("CDO.Message")
objEmail.From = """UPS"" <User#Example.com>"
objEmail.Subject = "This is a test"
Const ForReading=1
Set fso = CreateObject("Scripting.FileSystemObject")
Set dict = CreateObject("Scripting.Dictionary")
BodyText = fso.OpenTextFile("C:\Users\User\Desktop\UPS-Email.htm",ForReading).ReadAll
objEmail.HtmlBody = BodyText
'objEmail.AddAttachment "C:\Users\User\Desktop\test.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("C:\Users\User\Desktop\e.txt", 1)
row = 0
Do Until file.AtEndOfStream
line = file.Readline
dict.Add row, line
row = row + 1
objEmail.To = line
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "127.0.0.1"
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objEmail.Configuration.Fields.Update
objEmail.Send
Loop

You can't delete content from a file while you're reading the file. What you can do is truncate the file after you finished reading from it:
Do Until file.AtEndOfStream
...
Loop
file.Close
fso.OpenTextFile("C:\Users\User\Desktop\e.txt", 2).Close

Related

open all word docs in a folder and copy and paste contents back to excel

I have two versions of code that i have tried that are slightly different and neither works unfortunately. I need some help figuring out why and how to do what i need to do thanks
The first bit of code somehow immediately ends the loop and doesn't meet the initial conditional expression though I am not sure why because it should call all .docx files in that folder
the second bit of code throws an error Invalid Use of Property with this line Set wApp.Visible = True and I do not know why
First version
Dim folder As String
Dim doc As Document
folder = "G:\GAV\Educational On Assignment Folder\On Assignment Tour Reports\2019\On Tour Questionnaire"
file = Dir(folder & "*.dox*")
r = 1
Do While Len(file) < 0
Set doc = Documents.Open(Filename:=folder & file)
ActiveDocument.Selection.WholeStory
Selection.Copy
Workbooks("Reports Excel").Activate
Cells(1, r).Paste
doc.Close
r = r + 1
file = Dire
Loop
Second version
Dim wApp As Word.Application
Dim wDoc As Word.Document
Dim mySource As Object
Set obj = CreateObject("Scripting.FileSystemObject")
Set mySource = obj.getfolder("G:\GAV\Educational On Assignment Folder\On Assignment Tour Reports\2019\On Tour Questionnaire")
For Each file In mySource.Files(Word.Application)
If Len(file.Name) > 0 And InStr(1, file.Name, "$") = 0 Then
Set wApp.Visible = True
Set wDoc = wApp.Documents.Open(muSource & "\" & file.Name, , ReadOnly)
ActiveDocument.Selection.WholeStory
Selection.Copy
Workbooks("Reports Excel").Activate
Cells(1, r).Paste
doc.Close
r = r + 1
wApp.Quit
Set wApp = Nothing
End If
Next file
I need Excel to open each file in the folder, copy its entire contents and paste to a column in Excel. should be simple

How to replace if a character is repeated more than a threshold value with a null or "" in vbs?

Const ForReading = 1
Const ForWriting = 2
Set fso = CreateObject("Scripting.FileSystemObject")
strSource = "C:\Users\Desktop\test.csv"
Set File = fso.OpenTextFile(strSource, ForReading)
strText = File.ReadAll
File.Close
strNewText = Replace(strText,",","|")
Set File = fso.OpenTextFile(strSource, ForWriting, True)
File.WriteLine strNewText
File.Close
This is the code Im using and the result I get is:
xxxx|yyyy|zzzzz|||||||||||||||||||||
The pipe character '|' must be replaced with 'null' or '' if its repeated more than five times and I have tried using trim, replace and mid functions but couldn't get the solution. Thanks
You're trying to limit the "|" to 5 consecutive entries?
There may be a prettier way, but this would work
Do While InStr(1, strNewText, "||||||") > 0
strNewText = Replace(strNewText, "||||||", "|||||")
Loop
You could use the following regular expression:
\|{5,}
as follows:
Const ForReading = 1
Const ForWriting = 2
Set fso = CreateObject("Scripting.FileSystemObject")
path = "C:\Users\Desktop\test.csv"
Set file = fso.OpenTextFile(path, ForReading)
strText = file.ReadAll
file.Close
Set re = CreateObject("VBScript.RegExp")
re.Global = True
re.Pattern = "\|{5,}"
strNewText = re.Replace(strText, "")
Set file = fso.OpenTextFile(strSource, ForWriting, True)
file.WriteLine strNewText
file.Close
NB. Consider using Option Explicit at the beginning of your script; it will save you from misspelled and confused variables.

opening multiple text file in VBA as array

I've been using the code in this post to import several txt file. i want to put each value or string in one cell as array.but all of them put in one row so i have one column and several row.
the code is:
Sub ReadFilesIntoActiveSheet()
Dim fso As FileSystemObject
Dim folder As folder
Dim file As file
Dim FileText As TextStream
Dim TextLine As String
Dim Items() As String
Dim i As Long
Dim cl As Range
' Get a FileSystem object
Set fso = New FileSystemObject
' get the directory you want
Set folder = fso.GetFolder("G:\test")
' set the starting point to write the data to
Set cl = ActiveSheet.Cells(1, 1)
' Loop thru all files in the folder
For Each file In folder.Files
' Open the file
Set FileText = file.OpenAsTextStream(ForReading)
' Read the file one line at a time
Do While Not FileText.AtEndOfStream
TextLine = FileText.ReadLine
' Parse the line into | delimited pieces
Items = Split(TextLine, " ", 1)
' Put data on one row in active sheet
For i = 0 To UBound(Items)
cl.Offset(0, i).Value = Items(i)
Next
' Move to next row
Set cl = cl.Offset(1, 0)
Loop
' Clean up
FileText.Close
Next file
Set FileText = Nothing
Set file = Nothing
Set folder = Nothing
Set fso = Nothing
End Sub
Plz help me..
Thank you in advance
Here you are splitting the line and putting each token in different columns. If you don't want to split them, then remove these lines.
' Parse the line into | delimited pieces
Items = Split(TextLine, " ", 1)
' Put data on one row in active sheet
For i = 0 To UBound(Items)
cl.Offset(0, i).Value = Items(i)
Next
And then just add back cl.Value = TextLine

looping a DateLastModified function through a column in excel

I have a worksheet with data but I need to add the time at which the Data was created. This time is the "Last Modified"-time of the file I got the data from.
I already got all the filenames as in "filename.txt" in the first column of the worksheet so each line of data can be referenced to its file. I have this function to pull the LastModified-Date from the filename:
Function FileLastModified(strFullFileName As String)
strFullFileName = "C:\...\filefolder\" + Range("A1").Value
Dim fs As Object, f As Object, s As String
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(strFullFileName)
s = UCase(strFullFileName) & vbCrLf
s = f.DateLastModified
FileLastModified = s
Set fs = Nothing: Set f = Nothing
End Function
Now I want the function to go through all the filenames in column A and put all the LastModified-Times in column D. So how do I edit this
strFullFileName = "C:\.....\" + Range("A1").Value
to automatically pull the filename from the A-Column?
Something like this?
Dim FSO As Object: Set FSO = CreateObject("Scripting.FileSystemObject")
Dim i As Long
Dim n As Long
Dim filenames As Variant
Dim lastModifiedTimes As Variant
'How many filenames are there? (should tailor this to your exact situation)
n = Range("A:A").Find("*", Range("A1"), SearchDirection:=xlPrevious).Row
filenames = Range("A1").Resize(n, 1).Value 'load all fnames from sheet to array
ReDim lastModifiedTimes(1 To n, 1 To 1)
For i = 1 To n
lastModifiedTimes(i,1) = _
FSO.GetFile("C:\.....\" & filenames(i,1)).DateLastModified
Next i
'Slap times array onto sheet
Range("D1").Resize(n, 1).Value = lastModifiedTimes
Note that I got rid of your FileLastModified wrapper function since it's really only wrapping one thing, and it can be replaced by one single line of code.

Importing text files to Excel - lines from each file are placed in separate columns on same row

I found this code on this site but I haven't been able to adjust it for my own needs though I think it must be a very quick fix.
The code imports a series of text files to excel. A file is opened and the first line of this file is placed in A1, the second line in A2 and so on. When a new file is opened, the text is placed in the next available cell in column A (all files are read into column A).
I want to make a slight modification. I want the first line of file 1 in A1, the second line in B1 and so on (i.e. all the lines from File 1 are kept in Row 1). Then, the lines in File 2 are placed in Row 2, File 3 in Row 3 etc.
Any help would be greatly appreciated!
Sub ReadFilesIntoActiveSheet()
Dim fso As FileSystemObject
Dim folder As folder
Dim file As file
Dim FileText As TextStream
Dim TextLine As String
Dim Items() As String
Dim i As Long
Dim cl As Range
' Get a FileSystem object
Set fso = New FileSystemObject
' get the directory you want
Set folder = fso.GetFolder("D:\YourDirectory\")
' set the starting point to write the data to
Set cl = ActiveSheet.Cells(1, 1)
' Loop thru all files in the folder
For Each file In folder.Files
' Open the file
Set FileText = file.OpenAsTextStream(ForReading)
' Read the file one line at a time
Do While Not FileText.AtEndOfStream
TextLine = FileText.ReadLine
' Parse the line into | delimited pieces
Items = Split(TextLine, "|")
' Put data on one row in active sheet
For i = 0 To UBound(Items)
cl.Offset(0, i).Value = Items(i)
Next
' Move to next row
Set cl = cl.Offset(1, 0)
Loop
' Clean up
FileText.Close
Next file
Set FileText = Nothing
Set file = Nothing
Set folder = Nothing
Set fso = Nothing
End Sub
Yeap. Pretty easy. Just needed to adjust how your columns and rows are being offset and to not have it delimit each line as it's read.
See the adjusted code below:
Sub ReadFilesIntoActiveSheet()
Dim fso As FileSystemObject
Dim folder As folder, file As file, FileText As TextStream
Dim TextLine As String, Items() As String
Dim i As Long, cl As Range
' Get a FileSystem object
Set fso = New FileSystemObject
' get the directory you want
Set folder = fso.GetFolder("D:\YourDirectory\")
Dim x As Long
x = 1 'to offset rows for each file
' Loop thru all files in the folder
For Each file In folder.Files
' set the starting point to write the data to
Set cl = ActiveSheet.Cells(x, 1)
' Open the file
Set FileText = file.OpenAsTextStream(ForReading)
Dim i As Long
i = 0 'to offset columsn for each line
' Read the file one line at a time
Do While Not FileText.AtEndOfStream
TextLine = FileText.ReadLine 'read line
cl.Offset(, i).Value = TextLine 'fill cell
i = i + 1
Loop
' Clean up
FileText.Close
x = x + 1
Next file
Set FileText = Nothing
Set file = Nothing
Set folder = Nothing
Set fso = Nothing
End Sub
I'd think replacing all the references to rows and columns with each other would be sufficient. Try:
Replace cl.Offset(0, i).Value = Items(i) with cl.Offset(i, 0).Value = Items(i)
Replace Set cl = cl.Offset(1, 0) with Set cl = cl.Offset(0, 1)
Does that do the trick?

Resources