I want to extract some information from a text file.This is a line in my text file and I want to extract the numbers and save these numbers in an array.
ST/X 1000.0000000000000000 1400.0000000000000000 40.0000000000000000 25.0000000000000000 12.0000000000000000
The number of numbers are not fix(i.e in this example I have 5 numbers but it could be more or less) There are always 3 spaces between the numbers, but the length of numbers also are not fix(for example 1000.0000000000000000 has a length of 21, but 12.0000000000000000 has a length of 19). I wrote this block of code. but the problem of my code is that it returns the white space as the last number too. my code doesnt work correctly Did you have a better Idea for me to do this job better? thank you for your helps and ideas :)
my code:
Dim lngPos As Long
Dim lngCount As Long
Dim ifile As Integer
Dim Xarray() As String
Let ifile = FreeFile
Dim Name As String
Dim xi As Integer
Name = util1.fDateiName("*.txt", "Text")
'"C:\Dokumente und Einstellungen\bbastan\Desktop\test.txt"
'Open Name For Input As ifile
'While Not EOF(ifile)
'Line Input #ifile, entireline
ReDim Xarray(10)
xi = 0
Open Name For Input As ifile
lngPos = 1
While Not EOF(ifile)
Line Input #ifile, entireline
Do
lngPos = InStr(lngPos, entireline, Space(3))
If lngPos > 0 Then
xi = xi + 1
lngCount = lngCount + 1
lngPos = lngPos + 3
Xarray(xi) = Mid(entireline, lngPos, 21)
End If
Loop Until lngPos = 0
Wend
Dim I As Integer
If xi > 2 Then
MsgBox "ja"
For I = 1 To xi - 1
MsgBox Xarray(I)
Next I
Else
MsgBox "nein"
For I = 1 To xi
MsgBox Xarray(I)
Next I
The VBA Split() function might simplify things for you somewhat. It splits a string using a delimiter and puts the elements into an array. For example, the following test code...
Sub LineSplitTest()
Dim entireline As String, strArray() As String, thing As Variant
entireline = "ST/X 1000.0000000000000000 1400.0000000000000000 40.0000000000000000 25.0000000000000000 12.0000000000000000 "
strArray = Split(entireline, Space(3), -1, vbBinaryCompare)
For Each thing In strArray
thing = Trim(thing)
If Len(thing) > 0 Then
Debug.Print thing
End If
Next
Debug.Print "[done]"
End Sub
...prints this in the Immediate Window of the VBA IDE:
ST/X
1000.0000000000000000
1400.0000000000000000
40.0000000000000000
25.0000000000000000
12.0000000000000000
[done]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With