Options for parsing a text file to columns - excel

I am looking for some input and possible example for parsing a text file with the following format: (sorry not sure how to retain the formatting of the file in this text)
NAME ID FORMAT SHORT NAME
DESCRIPTION (this field is on the second row an indented by 5 spaces)
The first row (NAME, ID, FORMAT and SHORT NAME) always consist of just one row. The DESCRIPTION text may span multiple rows. In some cases, there is only a first row of NAME, ID, etc. without a corresponding DESCRIPTION row.
Here is an example of how the data looks in the file now:
NAME ID FORMAT SHORT NAME
DESCRIPTION
ABC 01 xx AB
abcdefg
hijklm
nopqrs
DEF 02 xx DE
abcedfg
hijklmnopqrst
GHI 03 xx.x GH
JKL 001 xx JKL
abcdef
ghijk
lmnopq
rstu
vwxyz
I would like to parse out the NAME, ID, FORMAT, SHORT NAME and DESCRIPTION into 5 separate columns in a csv or excel file for additional analysis. I don't care if the DESCRIPTION field is broken across multiple lines but it can also be concatenated into a single longer string.
Hope this all makes sense. Thanks in advance!

Providing the data for NAME,ID,FORMAT and SHORT NAME is aligned
beneath their header word then use those words on the first line
to calculate the start position and length of each field, then split
the lines into fields using Mid(). Join the description lines and write out to
the previous record before a new record is started. For example
Option Explicit
Sub ParseTextFile()
Const INFILE = "c:\temp\testfile.txt"
Const OUTFILE = "c:\temp\testfile.xlsx"
Dim wbOut As Workbook, ws As Worksheet, iRow As Long
Dim txt As String, ff As Integer, i As Integer, desc As String
Dim start(4) As Integer, length(4) As Integer
Dim count As Integer, msg As String
Set wbOut = Workbooks.Add
Set ws = wbOut.Sheets("Sheet1")
ws.Range("A1:E1") = Array("NAME", "ID", "FORMAT", "SHORT NAME", "DESCRIPTION")
ws.Columns("A:E").NumberFormat = "#"
iRow = 1
ff = FreeFile()
Open INFILE For Input As #ff
While Not EOF(ff)
count = count + 1
Line Input #ff, txt
If count = 1 Then
start(1) = InStr(1, txt, "NAME", vbTextCompare)
start(2) = InStr(1, txt, "ID", vbTextCompare)
start(3) = InStr(1, txt, "FORMAT", vbTextCompare)
start(4) = InStr(1, txt, "SHORT NAME", vbTextCompare)
For i = 1 To 3
length(i) = start(i + 1) - start(i)
Next
Else
If Left(txt, 1) = " " Then
desc = desc & Trim(txt) & " "
Else
' save the description from last record
ws.Cells(iRow, 5) = Trim(desc)
desc = ""
' new row
iRow = iRow + 1
length(4) = Len(txt) - start(4) + 1
For i = 1 To 4
ws.Cells(iRow, i) = Mid(txt, start(i), length(i))
Next
End If
End If
Wend
Close #ff
' final description
ws.Cells(iRow, 5) = Trim(desc)
' save result
ws.Columns("A:E").AutoFit
wbOut.Close True, OUTFILE
msg = count & " lines read from " & INFILE & vbCr & _
iRow - 1 & " rows written to " & OUTFILE
MsgBox msg, vbInformation
End Sub

Related

Transpose irregular data from .txt import to a table in Excel

I have imported a bunch of data from tables in Word -> .txt -> Excel, but in the conversion to .txt the format of the table is lost and I am now trying to recover it in Excel.
I would just make a simple Copy/Paste Macro based on the Cell Range, but the cell ranges are not the same across each imported .txt file so this won't work as the same data could be in A8 in one sheet then A10 in another.
You could almost move every other row into column B, but the "Date Due" field throws it out of sync.
I want to transpose the copied date into a more functional table format - see picture for example - which I can then analyze. I need to do this for hundreds of sheets but I'm hoping that if I can get it working for one then I can adapt it to work across many.
Each sheet may have multiple products, each new product is preceded by an integer (e.g. 1. Product1; 2. Product2 etc...)
deleted old code that I'd tried to do
EDIT2:
screenshot of typical notepad file
There is a load of text above this, but the first product always starts with QUOTATION MACHINE SCHEDULE, then 1. xxx
EDIT3:
Tried to add in the column I to have Quote Ref: and find this in the text file, but it didn't work. Code change from CDP1802 current solution below
'results sheet
Set ws = ThisWorkbook.Sheets("Results")
ws.Range("A1:I1") = Array("Item", "Date Due", "Type", "Serial Number", "Standard", "Mode", "Range", "Location", "Quote Ref:")
r = 1 ' output row
Select Case s
' match word to set column
Case "type": c = 3
Case "serial number": c = 4
Case "standard": c = 5
Case "mode": c = 6
Case "range": c = 7
Case "location": c = 8
Case "Quote Ref:": c = 9
Case Else: c = 0
End Select
New Screenshot for Quote Ref:
Read the text file into an array and then scan for key words using Select Case. Reading the data into an array allows you to select the value from the row below the key word.
update - Quote Ref added
Option Explicit
Sub ProcessTextFiles1()
Const FOLDER = "C:\temp\SO\Data\" ' folder where the text files are
Dim ws As Worksheet, sFilename As String, sQuoteRef As String
Dim n As Integer, i As Long, r As Long, c As Long
Dim fso As Object, ts As Object, ar() As String, s As String
Set fso = CreateObject("Scripting.FileSystemObject")
' results sheet
Set ws = ThisWorkbook.Sheets("Results")
ws.Range("A1:I1") = Array("Item", "Date Due", "Type", "Serial Number", _
"Standard", "Mode", "Range", "Location", "Quote Ref")
r = 1 ' output row
' scan each file in folder
sFilename = Dir(FOLDER & "*.txt")
Do While Len(sFilename) > 0
n = n + 1
sQuoteRef = ""
' open file and read into array
Set ts = fso.OpenTextFile(FOLDER & sFilename)
s = ts.readAll
s = Replace(s, vbLf, "")
ar = Split(s, vbCr)
ts.Close
'MsgBox sFilename & "=" & UBound(ar)
' parse the strings in the array
i = 0
Do While i <= UBound(ar)
s = LCase(Trim(ar(i)))
'Debug.Print s
If Len(s) > 0 Then ' skip blanks
If Left(s, 10) = "quote ref:" Then
sQuoteRef = ar(i + 1)
End If
If Left(s, 2) Like "#." Or Left(s, 3) Like "##." Then
' new product
r = r + 1
ws.Cells(r, 1) = ar(i)
ws.Cells(r, 9) = sQuoteRef
Else
Select Case s
' match word to set column
Case "type": c = 3
Case "serial number": c = 4
Case "standard": c = 5
Case "mode": c = 6
Case "range": c = 7
Case "location": c = 8
Case Else: c = 0
End Select
' take value below
If c = 4 Then
ws.Cells(r, 4) = ar(i + 1)
ws.Cells(r, 2) = ar(i + 2) ' due date
i = i + 2
ElseIf c > 1 Then
ws.Cells(r, c) = ar(i + 1)
i = i + 1
End If
End If
End If
i = i + 1
Loop
sFilename = Dir
Loop
MsgBox n & " Files processed", vbInformation
End Sub

Get all columns from Excel except selected

I have excel files converted to txt. In some files, some columns are skipped. That is controlled by database:
file | remove_column
=======+===============
file1 | CASE NOTE
-------+---------------
file2 | Description
-------+---------------
file3 | Item | Address
Remove_Column has the header (1st row). If several columns should be skipped, they are delimited with '|'
I have to compare converted txt file with original excel file if they match. How can I read all columns except those showed in DB table?
I am using UFT 12.5. Reading Excel through Excel.Application or ADO.
Thnx)
UPD: Code I use:
I have columns hard-coded:
Select Case OrigFileName 'file names come from database
Case "Fees mm-yy.xls"
ColumnNames = Split("1,2,3,4,5,6,7,8,9,10,11,12,13", ",")
Case "Exp mm-yy.xls"
ColumnNames = Split("1,2,3,4,5,6,7,8,9,12,13,14,15,16,19,20", ",")
End Select
But there are 50 files, and the business might ask to remove or to add back any columns; also, new files are coming...(((
Dim fsox : Set fsox = CreateObject("Scripting.FileSystemObject")
Dim TargFileRead : Set TargFileRead = fsox.OpenTextFile(targetFile)
Dim OrgExcel : Set OrgExcel = CreateObject("Excel.Application")
OrgExcel.Workbooks.Open(originalfile)
Set vSheet = OrgExcel.WorkSheets(TabUse) 'excel sheet name, comes from database
print vSheet.UsedRange.Rows.Count
For rc = 1 To vSheet.UsedRange.Rows.Count
For coc = 0 To UBound(ColumnNames) 'column names hard-coded
cc = cInt(ColumnNames(coc))
vtext = vSheet.cells(rc,cc)
If NOT(vtext=ChrW(9)) Then
If vstring="" Then
vstring=vtext
Else
vstring = vstring&vbTab&vtext
End If
End If
If len(vstring)>0 Then
TargFileText = TargFileRead.ReadLine
Do
If Left(TargFileText, 1)=ChrW(9) Then
TargFileText = MID(TargFileText, 2)
Else
Exit Do
End If
Loop
Do
If RIGHT(TargFileText, 1)=ChrW(9) Then
TargFileText= mid(TargFileText,1,len(TargFileText)-1)
Else
Exit Do
End If
Loop
TargFileStr = Trim(TargFileText)
If trim(vstring) = trim(TargFileStr) Then
' print "match"
Else
print "-=Not Match=-"&VBNewLine&"txt:::"&trim(TargFileStr)&VBNewLine&"xls:::"&trim(vstring)
End If
End If
Next
I would suggest to replace the Switch statement with a function call that gives you the relevant columns for the sheet as an array. The logic which column is allowed is then put in another function. That should make the logic more flexible than fixed columns.
Function getColumns(OrigFileName as String) As String()
Dim lastCol As Integer
Dim ColumnNumbers As String
lastCol = Sheets(OrigFileName).UsedRange.Columns.Count
For col = 1 To lastCol
If isColumnAllowed(OrigFileName, Sheets(OrigFileName).Cells(1, col)) Then
ColumnNumbers = ColumnNumbers & IIf(Len(ColumnNumbers) = 0, "", ",") & col
End If
Next
getColumns = Split(ColumnNumbers, ",")
End Function
Function isColumnAllowed(ByVal OrigFileName As String, columnName As String) As Boolean
Select Case OrigFileName
Case "file1"
Forbidden = Split("CASE NOTE", "/")
Case "file2"
Forbidden = Split("Description", "/")
Case "file3"
Forbidden = Split("Item/ Address", "/")
End Select
isColumnAllowed = (UBound(Filter(Forbidden, columnName)) = -1)
End Function
This is what I have now and is working:
If LEN(ColumnToRemove)>0 Then
ColumnToRemoveCol = split(ColumnToRemove, "|") 'set collection of header strings to skip column
For L = 1 To vSheet.UsedRange.Columns.Count
For x = 0 to UBound(ColumnToRemoveCol)
AddCol = 0 'ColumnToRemoveCol can have more than 1 item, that may cause any column to be added more than once; we will use the true/false logic via 0 and 1 to avoid that doubling
If vSheet.cells(1, l)=ColumnToRemoveCol(x) Then
AddCol = AddCol + 1
End If
Next
If AddCol =0 Then ColumnNumbers = ColumnNumbers&","&L
Next
Else
For L = 1 To vSheet.UsedRange.Columns.Count
ColumnNumbers = ColumnNumbers&","&L
Next
End If
If LEFT(ColumnNumbers, 1)="," Then ColumnNumbers=MID(ColumnNumbers, 2)
If RIGHT(ColumnNumbers, 1)="," Then ColumnNumbers=MID(ColumnNumbers, 1, LEN(ColumnNumbers)-1)
Printing the columns for first excel file in my case gives the next line:
ColumnNumbers: 1,2,3,4,5,6,7,8,10,11,12,15,16,17
Further usage:
getColumns = Split(ColumnNumbers, ",")
For rc = 1 To vSheet.UsedRange.Rows.Count
For coc = 0 To UBound(getColumns)
cc = cInt(getColumns(coc))
vtext = vSheet.cells(rc,cc)
.....
Next
Next

Parsing text files from Excel with string manipulation

Below is an example of a parsing program. It takes text from a text file and parses the data using string manipulation, and a couple loops:
Dim myFile As String
Dim text As String
Dim textline As String
Dim cstAct as integer
Dim actOpe as integer
Dim cusNam as integer
Dim act as integer
Dim reg as integer
myFile = "put file patch to text file here"
myFile = Application.GetOpenFilename()
Here is the do loop that I would like to pause once it reaches line 3 (the next account record)
Do Until EOF(1)
Line Input #1, textline
text = text & textline
Loop
cusAct = InStr(text, "ACCOUNT ")
actOpe = InStr(text, "ACCOUNT OPEN:")
reg = InStr(text, "REGION:")
cusNam = InStr(text, "CUSTOMER NAME:")
This is the for...loop I wish to execute once the do...loop stops or 'pauses once it reaches the next record
For i = 2 To ThisWorkbook.Worksheets("b2").Range("a65536").End(xlUp).Row
ThisWorkbook.Worksheets("name").Range("a" & i).Value = Mid(text, cstAct + 6, 9)
ThisWorkbook.Worksheets("name").Range("b" & i).Value = Mid(text, actOpe + 13, 27)
ThisWorkbook.Worksheets("name").Range("c" & i).Value = Mid(text, reg + 6, 9)
ThisWorkbook.Worksheets("name").Range("d" & i).Value = Mid(text, cusNam + 20, 19)
This is where I want to resume the 'do...loop' so that new the sub strings (ie 987654321 would be the new substring that results from Mid(text, cstAct + 6, 9)) of its respective parent string (ie ACCOUNT) refresh so to speak
otherwise, lines 1 and 2 will just loop over and over again.
next i
Below is an example of the sample text file:
ACCOUNT ABCDEF12
ACCOUNT OPEN: 05/10/15 ACT TYPE: PREMIUM
CUSTOMER NAME: JOHN B. SMITH CSA REP: 154983
CUSTOMER ADDRESS: 123 SOMEWHERE DRIVE SOMETHING HERE:
LAST ORDER: 06/24/2011 COUNTRY CODE: UNITED STATES
INVOICE #: 123456789 STATE CODE: CALIFORNIA
LAST MAINTENANCE: 01/02/15 COUNTY CODE: UNCODED
SOME INDICATOR: NO COMPLAINTS: NO IPM IND: DATAPREP/PERF4
SOME INDICATOR: NO STATUS: NONE AUTO RENEW: YES
SOMETHING HERE: NO
SOMETHING HERE: ABC IND:
SOMETHING HERE: 2 ABC ASSET NO: T
ACCOUNT ZXYFDG13
ACCOUNT OPEN: 05/10/15 ACT TYPE: PREMIUM
CUSTOMER NAME: JANE B. SMITH CSA REP: 154983
CUSTOMER ADDRESS: 123 SOMEWHERE DRIVE SOMETHING HERE:
LAST ORDER: 06/24/2011 COUNTRY CODE: UNITED STATES
INVOICE #: 123456789 STATE CODE: CALIFORNIA
LAST MAINTENANCE: 01/02/15 COUNTY CODE: UNCODED
SOME INDICATOR: NO COMPLAINTS: NO IPM IND: DATAPREP/PERF4
SOME INDICATOR: NO STATUS: NONE AUTO RENEW: YES
SOMETHING HERE: NO
SOMETHING HERE: ABC IND: NO
SOMETHING HERE: 2 REGION: NE
without adjusting the above code structure, output in excel will look like this:
A B C D
ROW 1 123456789 00/00/0000 NY JON SMITH
ROW 2 123456789 00/00/0000 NY JON SMITH
I am trying to get it to look like this:
A B C D
ROW 1 123456789 00/00/0000 NY JON SMITH
ROW 2 987654321 00/00/0000 FL JANE SMITH
Any thoughts on how to best do this?
If you know the literal structure of each "record type", then you can declare them as VBA User Defined Type structures for reading (and writing). Further, it looks like you can simplify your efforts with a slightly different code design and improve your error handling.
Consider how I would approach this problem using UDFs, which makes the code so much more readable and therefore, maintainable:-
'Always set this to ensure you have all variables declared
Option Explicit
'User Defined Types for each record format
Private Type AccountInfoType
OpenText As String * 18 'Absorb all text and prefixes up to data
OpenDate As String * 8 'Contains the data
AccTypeText As String * 24 'Absorb all text and prefixes up to data
AccType As String * 7 'Contains the data
'Add additional fields here
CRLF As String * 2 'CR/LF character
End Type
Private Type CustomerNameType
NameText As String * 18 'Absorb all text and prefixes up to data
Name As String * 20 'Contains the data
CsaRepText As String * 12 'Absorb all text and prefixes up to data
CsaRep As String * 6 'Contains the data
'Add additional fields here
CRLF As String * 2 'CR/LF character
End Type
Private Type AddressType
AddressText As String * 18 'Absorb all text and prefixes up to data
AddressData As String * 20 'Contains the data
SomethingHereText As String * 17 'Absorb remaining text
'Add additional fields here
CRLF As String * 2 'CR/LF character
End Type
Private Type LastOrderType
LastOrderText As String * 18 'Absorb all text and prefixes up to data
LastOrderDate As String * 10 'Contains the data
CountryText As String * 27 'Absorb all text and prefixes up to data
Country As String * 13 'Contains the data
'Add additional fields here
CRLF As String * 2 'CR/LF character
End Type
Private Type InvoiceType
InvoiceText As String * 18 'Absorb all text and prefixes up to data
InvoiceNumber As String * 9 'Contains the data
StateText As String * 28 'Absorb all text and prefixes up to data
State As String * 10 'Contains the data
'Add additional fields here
CRLF As String * 2 'CR/LF character
End Type
Sub ParseFile()
Dim wb As Workbook
Dim ws As Worksheet
Dim row As Long
Dim dataRecord As String
Dim accountNumber As String
Dim accountInfo As AccountInfoType
Dim customerName As CustomerNameType
Dim address As AddressType
Dim lastOrder As LastOrderType
Dim invoice As InvoiceType
Dim myFile As Variant
'Consider using proper error handling
On Error GoTo ParseFileZ
myFile = Application.GetOpenFilename()
If myFile = False Then
'Not a fan of GoTo but better than running the whole method inside if/then block
GoTo ParseFileX
End If
'I started with a new workbook. Change this to open an exsting workbook if desired
Set wb = Application.Workbooks.Add
'Set this handle to your desired worksheet
Set ws = wb.Worksheets(1)
'Set up column headers here. I chose row 3 to allow for a heading in row 1. Choose your own...
ws.Range("A3").Value = "Acc Number"
ws.Range("B3").Value = "Acc Opened"
ws.Range("C3").Value = "Region"
ws.Range("D3").Value = "Name"
'Base output row in the worksheet
row = 3
'Open the file in binary mode so that you can use User Defined Types to read each record
Open CStr(myFile) For Binary As #1
While Not EOF(1)
'Read next record
Input #1, dataRecord
'Find the first record of the next account - otherwise, skip until you get one
If Left(dataRecord, 7) = "ACCOUNT" And Len(dataRecord) = 16 Then
'Found the Account Number record. This is the start of the next account
accountNumber = Mid(dataRecord, 9, 8)
Get #1, , accountInfo 'Read the Account info record
Get #1, , customerName 'Read the Customer Name record
Get #1, , address 'Read the Address record
Get #1, , lastOrder 'Read the Last Order record
Get #1, , invoice 'read the Invoice record
'Ignore the remaining records unless you want to get more data. The "Read Next Record" loop will skip them
'Get the next row number on the output worksheet to write values to
row = row + 1
'Assign the values from the various records
ws.Cells(row, 1).Value = Trim(accountNumber)
ws.Cells(row, 2).Value = Trim(accountInfo.OpenDate)
ws.Cells(row, 3).Value = Trim(invoice.State) '(you talk about "region" but no region in data sample)
ws.Cells(row, 4).Value = Trim(customerName.Name)
'Add more cells for additional records you want to extra fields from here
End If
Wend
'We're finished. Close the file
Close #1
'Resize the cells for readibilty
ws.Cells.EntireColumn.AutoFit
ParseFileX:
'Disable error handling
On Error GoTo 0
'Be a good memory citizen
Set ws = Nothing
Set wb = Nothing
Exit Sub
ParseFileZ:
MsgBox Err.Number & " - " & Err.Description, "Error occurred"
Resume ParseFileX
End Sub

Excel: Give each number in a text/string its own cell

I have a text document full of 9 digit numbers. I need Excel to either read the text (.txt) file or a text cell and add each 9 digit number to each cell in a column.
Example text file:
123456789, 987654321, 213454321 / 987656789, [098752739]
Excel result:
123456789
987654321
213454321
987656789
098752739
Any advice?
You can use the standard Excel feature for importing data from Text file. Ribbon tab Data -> From Text.
From your result, with each cell containing the 9 digit number:
Click Data -> Text to columns
Select "Fixed Width"
You will then need to set break lines between each of your nine
digits
Optional: Click "Next" to format each of the fields
Finally, click "Finish"
You should now see each of the nine digits in a separate column.
Assuming your data is in a single cell, then your task has three parts:
read data from text file
parse each cell
store the results in a column
This code addresses only the second part:
Sub ParseData()
Dim s1 As String
s1 = Range("A1").Text
s1 = Replace(s1, " ", "|")
s1 = Replace(s1, "/", "|")
s1 = Replace(s1, "[", "|")
s1 = Replace(s1, "]", "|")
s1 = Replace(s1, ",", "|")
s1 = CleanUp(s1, "|")
ary = Split(s1, "|")
i = 1
For Each a In ary
Cells(i, 2).NumberFormat = "#"
Cells(i, 2).Value = a
i = i + 1
Next a
End Sub
Public Function CleanUp(sIN As String, sep As String) As String
Dim temp As String, temp2 As String, i As Long, CH As String
temp = sIN
While Left(temp, 1) = sep
temp = Mid(temp, 2)
Wend
While Right(temp, 1) = sep
temp = Mid(temp, 1, Len(temp) - 1)
Wend
temp2 = ""
For i = 1 To Len(temp)
CH = Mid(temp, i, 1)
If temp2 = "" Then
temp2 = CH
ElseIf CH <> sep Then
temp2 = temp2 & CH
ElseIf Right(temp2, 1) <> sep Then
temp2 = temp2 & CH
End If
Next i
CleanUp = temp2
End Function
NOTES:
The code replaces the various field separators with a single pipe. The data is then split using the pipe. The resulting array is then stored in cells:

Why is first entry skipping a line in Visual Basic command to compile text files into Excel?

The intention of my code below is to compile many text files into one Excel spreadsheet. I am able to retrieve data but the first command, to obtain the "gender" starts on the second line of the Excel spreadsheet; while the subsequent commands (e.g. get the "first name") correctly begin populating on the first line. Any ideas how to start "gender" on line 1 as well?
Sub read_text()
Set wb = Workbooks.Add
workingflnm = ActiveWorkbook.Name
i = 1 'First row
Set fd = CreateObject("Scripting.Filesystemobject")
pthnm = "C:\TestFolder"
Set fs = fd.GetFolder(pthnm)
For Each fl In fs.Files
If InStr(1, fl.Name, "txt", vbTextCompare) > 0 Then
Set Txtobj = CreateObject("Scripting.filesystemobject")
Set Txtfl = Txtobj.getfile(fl)
Set Txtstrm = Txtfl.openastextstream(1, -2)
Do While Txtstrm.atendofstream <> True
rdln = Txtstrm.readline
If InStr(1, rdln, "ender: ", vbTextCompare) > 1 Then
'This if/then looks for the "gender" value in each text file
x1 = InStr(1, rdln, "ender: ", vbTextCompare)
strg = Left(rdln, 40)
Workbooks(workingflnm).Sheets(1).Cells(i, 1) = strg
'i = i + 1
End If
If InStr(1, rdln, "irst Name: ", vbTextCompare) > 1 Then
'This if/then looks for the "first name" value in each text file
x1 = InStr(1, rdln, "irst Name: ", vbTextCompare)
strg = Left(rdln, 40)
Workbooks(workingflnm).Sheets(1).Cells(i, 2) = strg
'i = i + 1
End If
If InStr(1, rdln, "ast Name: ", vbTextCompare) > 1 Then
'This if/then looks for the "last name" value in each text file
x1 = InStr(1, rdln, "ast Name: ", vbTextCompare)
strg = Mid(rdln, x1 + Len("ast Name: "), x2 + 50 - (x1 + Len("ast Name: ")))
Workbooks(workingflnm).Sheets(1).Cells(i, 3) = strg
i = i + 1
End If
Loop
End If
Next
End Sub
The content of each text file looks like this:
Contact Information
Name: Smith, John Home Phone: 6465551234
Street Address: 1313 Mockingbird Work Phone:
Apt or Unit: Fax:
City/State/Zip: YONKERS,NY,10701 Email: john#john.john
County: Westchester
Contact Time: Respond Time:
--------------------------------------------------------------------------------------------------------------------------
User Info
First Name: John
Last Name: Smith
Date of Birth: 11/7/1957
Gender: Male
I think your method is fundamentally flawed. Because you are incrementing i at the wrong time. Because i is shared between each piece of data, every time you increment i you'll be on the next row.
My suggestion: Use ReadAll instead. Your data should have a delimiter in it so that you can parse each record and be certain you have the same row for the same record. If there is no delimiter, how do you know to go to a new record anyway?
This would make your code something like this:
dim currentRow as integer, i as integer, j as integer
dim data as string
currentRow = 1
'for each file you'll need to set up this loop
data = Txtstrm.ReadAll
records = Split(records, "YOURDELIMETER HERE")
For i = LBound(records) To UBound(records)
lines = Split(records, vbNewLine)
For j = LBound(lines) To UBound(lines)
rdln = lines(j)
If InStr(1, rdln, "ender: ", vbTextCompare) > 1 Then
'This if/then looks for the "gender" value in each text file
x1 = InStr(1, rdln, "ender: ", vbTextCompare)
strg = Left(rdln, 40)
Workbooks(workingflnm).Sheets(1).Cells(i + 1, 1) = strg
'Do not increment i manually as that is handled by for loop
End If
' etc...
Next
Next
currentRow = currentRow + i
'next file

Resources