I hope you can help with a VBA problem I'm trying to solve.
My situation:
I have multiple txt files as input for the search of a particular string ("tflux"). In every txt file the string is present so it is not possible that it is not found. I've written the code below, but I cannot find a way to tell excel that after copying the value that is related to the found string it has to move one cell lower for the next found value that is related to the next file it searches. Although I didn't try yet, I also would like excel to print the file name next to the numbers to be sure that the values correspond to a certain file name.
My VBA code so far:
Sub CommandButton1_Click()
Dim strF As String, strP As String, text As String, textline As String, tFlux As Integer
strP = "C:\test" 'change for the path of your folder
strF = Dir(strP & "\*.txt") 'Change as required
Do While strF <> vbNullString
Open strF For Input As #1
Do Until EOF(1)
Line Input #1, textline
text = text & textline
tFlux = InStr(text, "tflux")
Range("B2").Value = Mid(text, tFlux + 9, 3) <----- this is the line where I need help, Now the last found value is copied into cell B2, but I want excel to move to B3 after filling B2, move to B4 after filling B3, etc....
Loop
Close #1
text = ""
strF = Dir()
Loop
End Sub
The answer of VBA Pete will do the desired moving down for each found value. But I want to warn you about another, important problem in your code:
Line Input #1, textline
text = text & textline
tFlux = InStr(text, "tflux")
The above code has two problems. First, each time you read a line you append it to the previous text from the file, and you restart the search from the file's beginning. This is very slow, but moreover, it is wrong because if there are many occurrences of "tflux" in the file, you will always catch the first occurrence. Even if there is only one occurrence, you will catch it and report it many times each time you read a new line.
The second line of the above could should be rewritten this way:
text = textline ' <-- just copy the line, don't append it to previous lines from the file
How about a long variable that moves one value up in the range each time it runs through the loop:
Sub CommandButton1_Click()
Dim strF As String, strP As String, text As String, textline As String
Dim tFlux As Integer strP = "C:\test" 'change for the path of your folder
Dim x as long
strF = Dir(strP & "*.txt") 'Change as required
Do While strF <> vbNullString
x = 2
Open strF For Input As #1 Do Until EOF(1)
Line Input #1, textline
text = text & textline
tFlux = InStr(text, "tflux")
Range("B" & x).Value = Mid(text, tFlux + 9, 3)
x = x + 1
Loop
Close #1 text = "" strF = Dir() Loop
End Sub
I would recommend that you refactor your code as follows:
Sub CommandButton1_Click()
Dim strF As String, strP As String, textline As String, tFlux As Integer
Dim r As Long ' to keep track of which row we are writing to
strP = "C:\test" 'change for the path of your folder
strF = Dir(strP & "\*.txt") 'Change as required
r = 2 ' first line of output will go to row 2
Do While strF <> vbNullString
Open strF For Input As #1
Do Until EOF(1)
Line Input #1, textline
tFlux = InStr(textline, "tflux")
'See if we found "tflux"
If tFlux > 0 Then
'Found it - store the associated value
Cells(r, "B").Value = Mid(textline, tFlux + 9, 3)
'Store the filename too
Cells(r, "C").Value = strF
r = r + 1 ' set row pointer ready for next file
Exit Do ' found and processed - no need to keep looking within this file
End If
Loop
Close #1
strF = Dir()
Loop
End Sub
I included an Exit Do inside the "read file" loop so that, as soon as it finds the information you are looking for, it exits the loop. That saves time by not having to continue reading the rest of the file looking for something that you know won't be there.
Related
I am designing a VBA function for collecting specific data from various text files. Currently, the function works perfect with single file. However, I would like to expand it for looping multiple text files.
Sub onlinecharges()
Workbooks.Add
Dim myFolder As String, mtext As String, textline As String, po_charges As Integer
myFolder = Application.GetOpenFilename()
Open myFolder For Input As #1
Do Until EOF(1)
Line Input #1, textline
text = text & textline
Loop
Close #1
po_charges = InStr(text, "NET CHARGES")
ActiveWorkbook.Sheets(1).Cells(2, 1).Value = Dir(myFolder)
ActiveWorkbook.Sheets(1).Cells(2, 2).Value = Abs(Mid(text, po_charges + 88, 8))
End Sub
The currently put the file name in A2, specific data in B2.
My desire outcome is file names in A2 up to Ai, specific data in B2 to Bi.
So, how I can add a loop for scanning multiple selected text files?
Much appreciate! Thank you!
In this solution it allows to select multiple text files.
Sub LoopAllSelectedTextFilesInAFolder()
Dim rw As Integer: rw = 2
' Loop through all files in a folder
Dim Filename As Variant
Filename = Application.GetOpenFilename(FileFilter:="Text Files (*.txt), *.txt", Title:="Select file(s)", MultiSelect:=True)
' Check if Cancel button was pressed
If Not IsArray(Filename) Then
MsgBox " No files selected!", vbInformation
Exit Sub
End If
Application.ScreenUpdating = False
' Loop through selected files
Dim i As Integer
For i = 1 To UBound(Filename)
Open Filename(i) For Input As #1
Do Until EOF(1)
Line Input #1, textline
Text = Text & textline
Loop
Close #1
' Write filename & Text
ActiveWorkbook.Sheets(1).Cells(rw, 1).Value = Filename
ActiveWorkbook.Sheets(1).Cells(rw, 2).Value = Text
' next row
rw = rw + 1
' Clear Text
Text = ""
Next i
Application.ScreenUpdating = True
End Sub
I need one value from multiple text files. Those text files are stored with a 5-digit filename in a folder(Around 1000 files) and I would like to create a macro, which scans this folder for a subset of files and then extract an individual Euro value.
I got the extraction part going, but I'm not able to loop this process through different file names yet as I'm fairly new to VBA.
Sub ExtractData()
Dim myFile As String, text As String, textline As String, Data As Integer, filename As String
Dim myFolder As String
myFolder = "C:\Folder\"
filename = Range("A1").Value & ".txt"
myFile = "C:\Folder\" & filename & ""
Open myFile For Input As #1
Do Until EOF(1)
Line Input #1, textline
text = text & textline
Loop
Close #1
Data = InStr(text, "Euro")
Range("B1").Value = Mid(text, Data + 6, 4)
End Sub
I would highly appreciate it if someone would point me in the right direction.
Greetings
You may use Scripting.FileSystemObject to iterate the files in the target folder, use the Like operator to validate the file name and then get the value from each file as usual.
This should work:
Sub ExtractData()
Dim folderPath As String, filePath As String
Dim textline As String, data As Integer
folderPath = "C:\Folder\"
Dim oFso As Object: Set oFso = CreateObject("Scripting.FileSystemObject")
Dim oFolder As Object: Set oFolder = oFso.GetFolder(folderPath)
Dim oFiles As Object: Set oFiles = oFolder.Files
Dim oFile As Object
Dim counter As Integer
For Each oFile In oFiles
If Not oFile.Name Like "#####.txt" Then GoTo ContinueFor
data = 0
counter = counter + 1
Range("A" & counter).Value = oFile.Name
filePath = folderPath & oFile.Name
Open filePath For Input As #1
Do Until EOF(1) Or data > 0
Line Input #1, textline
data = InStr(textline, "Euro")
Loop
Close #1
If data > 0 Then Range("B" & counter).Value = Mid(textline, data + 6, 4)
ContinueFor:
Next
End Sub
This will extract the target value from the first line that contains the word "Euro". If the value that you're trying to extract is not in the same line, you can read the whole text (similar to what you did originally) and then extract the value you want:
Dim allText As String
' ...
' ...
Open filePath For Input As #1
allText = Input(LOF(1), 1)
Close #1
data = InStr(allText, "Euro")
If data > 0 Then Range("B" & counter).Value = Mid(allText, data + 6, 4)
There are probably better ways but it all depends on the structure of your file (which you haven't shown). For example, if the target value is in the next line and you know its position in that line, you could use the original code above to read the line that contains the word "Euro", read the next line, and then extract the value.
Good afternoon all,
I am building an excel sheet for my coworkers to use to generate CSV files. I need to get an output with header row and then all the data from the sheet. It will be no more than 40 rows, but could be less rows. I currently have a lot of formulas in the sheet doing the heavy lifting for my coworkers on things like generating usernames/etc from the input data. I need to have them click a button and get the CSV file on the other end. My current issues are as follows.
1.) my CSV contains double quotes on every field, even though commas should not be in the input data. I need to prevent this as the program we are feeding these csv files to does not like the double quotes AT ALL. Yes, I know you can open it in notepad and replace all to remove them but im trying to build a one click solution as some of the folks using this are not very tech savvy.
2.) my macro is exporting all forty rows of data currently. I need it to only export the rows that contain data. Theoretically with the formulas built there should be no "partial" rows, only a full row or a blank row.
3.) When generating the CSV file its not appending a filetype at all, I need it to specify a .txt. filetype if at all possible as again, the program we are feeding these to is very picky.
Sub CommandButton1_Click()
Dim filename As String
Dim myFile As String, rng As Range, cellValue As Variant, i As Integer, j As Integer
filename = InputBox("Please enter file name", "Save as CSV", "CSV_" & Format(Now, "DD_MM_yyyy"))
myFile = Application.DefaultFilePath & filename
Set rng = Range("A1:J41")
Open myFile For Output As #1
For i = 1 To rng.Rows.Count
For j = 1 To rng.Columns.Count
cellValue = rng.Cells(i, j).Value
If j = rng.Columns.Count Then
Write #1, cellValue
Else
Write #1, cellValue,
End If
Next j
Next i
Close #1
End Sub
This is what your code would have to look like. Unfortunately I wasn't able to get rid of the double quotes, maybe someone else has an idea for that.
Sub csvExport()
Dim filename As String
Dim myFile As String, cellValue As Variant, i As Integer, j As Integer
Dim ws As Worksheet
filename = "\" & InputBox("Please enter file name", "Save as CSV", "CSV_" & Format(Now, "DD_MM_yyyy")) & ".txt"
myFile = Application.DefaultFilePath & filename
Set ws = Worksheets("YOURSHEETNAME")
With ws
Open myFile For Output As #1
For i = 1 To .UsedRange.Rows.Count
For j = 1 To .UsedRange.Columns.Count
cellValue = .Cells(i, j).Value
If j = .UsedRange.Columns.Count Then
Write #1, cellValue
Else
Write #1, cellValue,
End If
Next j
Next i
Close #1
End With
End Sub
I really hope i can get your help.
Ive been searching high and low for what is probably a simple solution.
We have hundreds of txt files that all relate to cnc programs. Unfortunately there has been a historical lack of control in keeping a strict numbering system for parts and operations.
I have to extract the 3rd and 4th line of txt from each file into an excel doc so we can remunerate some and catalogue all for referencing.
So far the closest thing i've found to what i'm after is in the thread
Extract a single line of data from numerous text files and import into Excel
however i cannot make it work - my excel knowledge is good but not with macros.
the start of every txt file is
#1 <blank line>
#2 %
#3 O00000 (part description)
#4 (part descriptio)
#5 rest of program.
.
.
.
as requested ive included the code i'm trying to modify.
Private Sub CommandButton1_Click()
Dim filename As String, nextrow As Long, MyFolder As String
Dim MyFile As String, text As String, textline As String, prog As String
MyFolder = "M:\CNC Programs\Haas lathe programs\Haas ST30 programs\Programs\Programs in .txt format"
MyFile = Dir(MyFolder & "*.txt")
Do While MyFile <> ""
Open (MyFolder & MyFile) For Input As #1
Do Until EOF(1)
Line Input #3, textline
text = text & textline
Loop
Close #1
MyFile = Dir()
Debug.Print text
nextrow = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row + 1
Sheet1.Cells(nextrow, "A").Value = Mid(text, prog)
text = "" 'reset text
Loop
End Sub
Since you don't have much experience with vba, here are some points you might want to google and put the results together
Open a Text File in Excel VBA (you should start with that, and try to read one file)
Loop through all files in a certain folder with Excel VBA
Your code needs to do the following.
get a list of all the files you want to load
open each file of that list
read the 3rd and 4th line from that file
copy the lines to excel.
There are lots of examples on the internet, once you learn how to search
after a few hours and some help from a friend we came up with this, does more or less what i needed.
I know how I want to improve it, I just need to figure that out now. Again, I'm sure its a simple trick. Perseverance!!!
What I want to do with this now, if you can, is take my directory
'M:\CNC Programs\Haas Mills programs\All Mill Programs .txt format\'
and scan all subsequent folders for said .txt files and extract the same info into a workbook.
If I figure it out I'll update the post again.
Thanks for setting me on the right path Mister 832.
Private Sub CommandButton1_Click()
Dim MyMask As String, nextrow As Long, MyFolder As String
Dim MyFile As String, text As String, textline As String
Dim posCommentStart As String, posCommentFinish
Dim iLine As Integer
MyFolder = "M:\CNC Programs\Haas Mills programs\All Mill Programs .txt format\HAAS MINI-MILL BALLPADS & BALLPINS\"
MyMask = MyFolder & "*.txt"
MyFile = Dir(MyMask)
Do While MyFile <> ""
iLine = 0
Open (MyFolder & MyFile) For Input As #1
Do Until EOF(1) Or iLine >= 4
iLine = iLine + 1
Line Input #1, textline
If iLine >= 3 Then
text = text & textline 'second loop text is already stored -> see reset text
End If
Loop
Close #1
MyFile = Dir()
Debug.Print text
posCommentStart = InStr(text, "(")
posCommentFinish = InStr(text, ")")
If posCommentStart > 0 Then
nextrow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row + 1
ActiveSheet.Cells(nextrow, "A").Value = Left(text, posCommentStart - 2)
ActiveSheet.Cells(nextrow, "B").Value = Mid(text, posCommentStart + 1, posCommentFinish - posCommentStart - 1)
End If
text = "" 'reset text
Loop
End Sub
I need to select a text file to import into Excel where the name of the text file contains a string of text that matches a cell in the Excel spreadsheet.
Eg.
A cell with a value "D12345"
I need to import a text file into the sheet where the same string (i.e. "D12345") is contained in the name of the text file.
The selection needs to be made from a collection of text files. Only 1 file in the collection will contain the matching string.
Hope that makes sense.
Give this a try:
Sub SimpleFileListre()
Dim s As String, FileName As String
Dim mesage As String
Range("A:A").Clear
s = "C:\TestFolder\*.txt"
sFolder = "C:\TestFolder\"
FileName = Dir(s)
Do Until FileName = ""
If InStr(1, FileName, "D12345") > 0 Then
Call GetStuff(sFolder & FileName)
End If
FileName = Dir()
Loop
End Sub
Sub GetStuff(s)
Close #2
Open s For Input As #2
j = 1
Do While Not EOF(2)
Line Input #2, TextLine
Cells(j, 1) = TextLine
j = j + 1
Loop
Close #2
End Sub