aishwarya gowda
New Member
VBA: split string by random number of spaces and extract string in particular position:
I have a a lengthy text file(which is the output of engineering sofware) with multiple lines in it.
sample of my text file : test1.txt
#
[keyword] 1140.0-1200.0 sec 100 MB 100 km/sec
[keyword] 1080.0-1200.0 sec 200 MB 17.1 km/sec
[keyword] 1020.0-1200.0 sec 300 MB 160 km/sec
[keyword] 960.0-1200.0 sec 400 MB 15.9 km/secs
#
Difficulties:
1.The number of spaces are random in the line.
2.Need to extract the 6th string in each line (each string is separated by spaces)
ex: 100
17.1
160
15.9
3.Excel template is already ready, Need to place the values extracted in a 2nd column, sample template looks like when the values are added is attached:
4. starting row : 4, column number: 2
5.split is used to convert string into an array, but unable to proceed further.
code sample i have : to fetch file from the path
"
>>> use code - tags <<<
"
I have a a lengthy text file(which is the output of engineering sofware) with multiple lines in it.
sample of my text file : test1.txt
#
[keyword] 1140.0-1200.0 sec 100 MB 100 km/sec
[keyword] 1080.0-1200.0 sec 200 MB 17.1 km/sec
[keyword] 1020.0-1200.0 sec 300 MB 160 km/sec
[keyword] 960.0-1200.0 sec 400 MB 15.9 km/secs
#
Difficulties:
1.The number of spaces are random in the line.
2.Need to extract the 6th string in each line (each string is separated by spaces)
ex: 100
17.1
160
15.9
3.Excel template is already ready, Need to place the values extracted in a 2nd column, sample template looks like when the values are added is attached:
4. starting row : 4, column number: 2
5.split is used to convert string into an array, but unable to proceed further.
code sample i have : to fetch file from the path
"
>>> use code - tags <<<
Code:
Sub test()
Dim ReadData As String
Dim myFile As String
' Column
Dim vntCC As Variant: vntCC = Array(2)
' Row Array
Dim vntFR As Variant: vntFR = Array(4)
myFile = "C:\Users\test1.txt"
Open myFile For Input As #1
Do Until EOF(1)
Line Input #1, ReadData
Call WriteLineToColumn(ReadData)
Loop
End Sub
"
code sample 2: used split to convert string into array
"
Sub WriteLineToColumn(s As String)
'Converts the string of data to an array
'iterates the array and puts non-empty elements in to successive rows within Column(col)
Dim r As Long 'row counter
Dim dataElement As Variant
Dim i As Long 'array element counter
Dim t As Long 'Total records counter
Dim strLine As String 'current line in text file
For i = LBound(Split(s, " ")) To UBound(Split(s, " "))
dataElement = Trim(Split(s)(i))
If Not dataElement = vbNullString Then
r = r + 1
Range(r, col).Value = dataElement
End If
Next
End Sub
Attachments
Last edited by a moderator: