Text File Column Data Extraction with Excel VBA - vba

I have code below that extracts data from a text file and sends to a worksheet. Data sends to the worksheet but its a mess. I aim to extract certain columns of data in the text file. Data columns are space delimited and spacing differs between column but ea column has a heading. How can I complete my code to search text file by column header name and send data under that header to the worksheet? A typical header and columns of data underneath is shown below the code. Header blocks and associated data are repeated throughout the text file but are space delimited by rows. Above ea header band is an identifier for that block.
Sub test()
Dim Path As String
Dim textline As String
Dim arr() As String
Dim i As Long, j As Long
Path = whatever...
Open Path For Input As #1
i = 1
While EOF(1) = False
Line Input #1, textline
arr = Split(CStr(textline), " ")
For j = 1 To UBound(arr)
ActiveSheet.Cells(i, j).Value = arr(j - 1)
Next j
i = i + 1
Wend
Close #1
End Sub
Identifier 1.1
Heave /
Wave Ampl.
/--------------/
Ampl. Phase
0.123 42
0.131 72
0.433 55

Related

VBA test format of text/value

I'm making a sub that exports a DXF file as text into my sheet and then take some values out of that.
I have two problems :
--> The first being how to keep the format of a value I export in a sheet?
--> And the second one being how to test the format of a value ?
I have different types of value in the file that I'm exporting :
Text
Integer "10", "20", "21" etc.. which tells me what kind of value comes after
Actual values that I want (which kind was given by the integer), written as xxx.xxxx ("0.0000", "50.0000" or 120.0000 for example so always 4 zeros after the dot)
In the file it looks like this :
CONTINUOUS
10
50.0000
20
120.0000
30
0.0000
40
50.0000
50
0.0000
51
180.0000
62
5
0
So my issue is that excel doesn't keep my values as they are when I export it. If it is 50.0000 it will write 50 and then I can't differentiate the types of the values... All the solution I found were about getting all my data as a format #.000 but that doesn't solve my problem...
Here is my sub :
Sub ImportDXF()
Dim fName As String
ActiveSheet.Columns(1).ClearContents
fName = Application.GetOpenFilename("DXF Files (*.dxf), *.dxf")
If fName = "False" Then Exit Sub
Dim v As Variant
Dim r As Long
r = 2 'from row 2
Open fName For Input As #1
Do While Not EOF(1)
Input #1, Line$
Rows(r).Columns(1) = Trim(Line$)
r = r + 1
Loop
Close #1
End Sub
And then I have another sub that will make something with the values I have exported so I want to test if this is an integer value or a float..
You'll have to test each value as you read it from the input DXF file. Then, apply an appropriate format to the cell with that value so it shows properly in your spreadsheet.
Sub ImportDXF()
Dim fName As String
ActiveSheet.Columns(1).ClearContents
fName = Application.GetOpenFilename("DXF Files (*.dxf), *.dxf")
If fName = "False" Then Exit Sub
Dim v As Variant
Dim r As Long
r = 2 'from row 2
Open fName For Input As #1
Do While Not EOF(1)
Input #1, Line$
If IsNumeric(Line$) Then
'--- we have a number, but what kind?
If InStr(1, Line$, ".", vbTextCompare) > 0 Then
'--- we have a VALUE, so format to show the decimals
Cells(r, 1).NumberFormat = "#0.0000"
Else
'--- we have a value ID, format with no decimals
Cells(r, 1).NumberFormat = "#0"
End If
Else
'--- we have text
Cells(r, 1).NumberFormat = "#"
End If
Cells(r, 1).Value = Trim(Line$)
r = r + 1
Loop
Close #1
End Sub

Converting .txt file directly into an array with custom delimiter

I am converting a .txt file directly into an array in excel VBA. The default delimiter is a "," (comma) and I need to change it to "vblf". I am having trouble figuring out how to do that with the code I have today.
Please help
Const strFileName As String = [file]
Dim CONFIGTXT(1 To 13000) As String
Dim intFileNum As Integer
Dim intCount As Integer
Dim strRecordData As String
intFileNum = FreeFile
intCount = 1
Open strFileName For Input As #intFileNum
Do Until EOF(intFileNum) Or intCount > 13000
Input #intFileNum, strRecordData
CONFIGTXT(intCount) = strRecordData
intCount = intCount + 1
Loop
Close #intFileNum
Range("Q2:Q" & UBound(CONFIGTXT) + 1) = WorksheetFunction.Transpose(CONFIGTXT)
Change
Input #intFileNum, strRecordData
to
Line Input #intFileNum, strRecordData
Input is intended to read in data that is comma-delimited, one variable at a time. For example, if you had data of
12345,789
and used the statement
Input #intFileNum var1, var2
then var1 would be given the value 12345 and var2 would be given the value 789.
Line Input is intended to read a line at a time, delimited by the new line character (normally CR/LF).
Note: If your data has information separated by line feeds, this will NOT separate those portions into separate entries in the array. So if your data contains
xxx/xxx/xxx
where the / is actually a line feed, that entire record will be placed into one cell in the final output.

Writing Fixed width text files from excel vba

This is the output of a program.
I have specified what shall be width of each cell in the program and my program shows correct output.
What I want to do is cell content shall be written from right to left. E.g highlighted figure 9983.54 has width of 21. Text file has used first 7 columns. But I want it to use last 7 columns of text file.
Please see expected output image.
I am not getting any clue how to do this. I am not a very professional programmer but I love coding. This text file is used as input to some other program and i am trying to automate writing text file from excel VBA.
Can anyone suggest a way to get this output format?
Here is the code which gave me first output
Option Explicit
Sub CreateFixedWidthFile(strFile As String, ws As Worksheet, s() As Integer)
Dim i As Long, j As Long
Dim strLine As String, strCell As String
'get a freefile
Dim fNum As Long
fNum = FreeFile
'open the textfile
Open strFile For Output As fNum
'loop from first to last row
'use 2 rather than 1 to ignore header row
For i = 1 To ws.Range("a65536").End(xlUp).Row
'new line
strLine = ""
'loop through each field
For j = 0 To UBound(s)
'make sure we only take chars up to length of field (may want to output some sort of error if it is longer than field)
strCell = Left$(ws.Cells(i, j + 1).Value, s(j))
'add on string of spaces with length equal to the difference in length between field length and value length
strLine = strLine & strCell & String$(s(j) - Len(strCell), Chr$(32))
Next j
'write the line to the file
Print #fNum, strLine
Next i
'close the file
Close #fNum
End Sub
'for example the code could be called using:
Sub CreateFile()
Dim sPath As String
sPath = Application.GetSaveAsFilename("", "Text Files,*.txt")
If LCase$(sPath) = "false" Then Exit Sub
'specify the widths of our fields
'the number of columns is the number specified in the line below +1
Dim s(6) As Integer
'starting at 0 specify the width of each column
s(0) = 21
s(1) = 9
s(2) = 15
s(3) = 11
s(4) = 12
s(5) = 10
s(6) = 186
'for example to use 3 columns with field of length 5, 10 and 15 you would use:
'dim s(2) as Integer
's(0)=5
's(1)=10
's(2)=15
'write to file the data from the activesheet
CreateFixedWidthFile sPath, ActiveSheet, s
End Sub
Something like this should work:
x = 9983.54
a = Space(21-Len(CStr(x))) & CStr(x)
Then a will be 14 spaces followed by x:
a = " 9983.54"
Here 21 is the desired column width --- change as necessary. CStr may be unnecessary for non-numeric x.
If you're going to right-justify a lot of different data to different width fields you could write a general purpose function:
Function LeftJust(val As String, width As Integer) As String
LeftJust = Space(width - Len(val)) & val
End Function
The you call it with LeftJust(CStr(9983.54), 21).
Also note that VBA's Print # statement has a Spc(n) parameter that you can use to produce fixed-width output, e.g., Print #fNum, Spc(n); a; before this statement you calculate n: n = 21-Len(CStr(a)).
Hope that helps

Reading formatted data from a text file

The following code reads in values (in a loop) from a text file containing two numbers per line into X and Y. The first iteration of the loop gives correct values for X and Y (70, 210). The next iteration onwards, the X and Y values are not what is contained in the file (210, 210 for the second iteration instead of 0, 210). I ust be making a mistake but I can't seem to find it !
Sub main()
Dim X As Double
Dim Y As Double
Open "perforatedcircles.txt" For Input As #1
Do While Not EOF(1)
Input #1, X, Y
Loop
Close #1
End Sub
Sample Contents of "perforatedcircles.txt":
70.000 210.000
0.000 210.000
-70.000 -210.000
How was the input file created? It appears to be in a different format than the Input # directive is expecting.
https://msdn.microsoft.com/en-us/library/aa243386(v=vs.60).aspx
"Data read with Input # is usually written to a file with Write #. Use this statement only with files opened in Input or Binary mode."
"Note To be able to correctly read data from a file into variables using Input #, use the Write # statement instead of the Print # statement to write the data to the files. Using Write # ensures each separate data field is properly delimited."
Given the space delimitation, you'll need to parse the file differently. Here is one example:
Dim iLine As Integer,
Dim sFile As String
Dim sData As String
Dim sLine() As String
Dim sSplitLine() As String
Dim x as Double
Dim y as Double
'read the whole file into 1 string variable
sFile = "perforatedcircles.txt"
Open sFile For Input As #1
sData = Input(LOF(1), 1)
Close #1
sLine = Split(sData, vbCrLf)
For iLine = 0 To UBound(sLine)
sSplitLine = Split(sLine(UBound(sLine)), " ")
x = CDbl(sSplitLine(0))
y = CDbl(sSplitLine(1))
'Do Stuff with your numbers here
Next iLine

Reading data from text file and delimiting

I have an Excel 2010 spreadsheet, and I am reading in information from a .txt file (and another .xls file in future).
This text file has 3 elements per row; firtname, surname and Job title, and each element is separated by a comma. I have the data reading and pasting into Excel, however each row is pasted into the one cell. I am looking to paste each element into different columns. I know that I should try and delimit, but I just can't figure out the syntax.
My question is how do I separate each element and paste it into it's own cell? I currently use commas to separate each element on my .txt file, but future files might use tabs, full-stops, semi-colons etc. How do I extend it so all bases are covered?
Below is my code, and under my code is a sample of dummy data
Sub FetchDataFromTextFile()
Dim i As Long
Dim LineText As String
Open "C:\mytxtfile.txt" For Input As #24
i = 2
While Not EOF(24)
Line Input #24, LineText
ActiveSheet.Cells(i, 2).Value = LineText
P = Split(Record, ",")
i = i + 1
Wend
Close #24
End Sub
John, Doe, Boss
Johnny, Steele, Manager
Jane, Smith, Employee
NOTE: Competant in other programming languages, however not done VB in about 6 or 7 years. I can never seem to wrap my head around VB Syntax, so please treat me like a novice for this.
Sub FetchDataFromTextFile()
Dim i As Long
Dim LineText As String
Open "C:\mytxtfile.txt" For Input As #24
i = 2
While Not EOF(24)
Line Input #24, LineText
Dim arr
arr = Split(CStr(LineText), ", ")
For j = 1 To
ActiveSheet.Cells(i, j).Value = arr(j - 1)
Next j
i = i + 1
Wend
Close #24
End Sub
For different delimiters, make use of the answers in here