2013-05-07 73 views
3

我想從文本文件中提取一些信息。這是我的文本文件中的一行,我想提取數字並將這些數字保存在數組中。使用vba從文本中提取信息

ST/X 1000.0000000000000000 1400.0000000000000000 40.0000000000000000 25.0000000000000000 12.0000000000000000 

數的數目並不固定(即,在這個例子中我有5個數字,但它可以是更多或更少) 總是有數字3米之間的空間,但編號的長度也沒有固定(例如1000.0000000000000000的長度爲21,但12.0000000000000000的長度爲19)。我寫了這段代碼。但我的代碼的問題是,它也返回了最後一個數字的空格。我的代碼無法正常工作 您是否有更好的想法讓我更好地完成這項工作? 感謝您的幫助和想法:)

我的代碼:

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 
+2

你可以使用[分割功能(HTTP:// msdn.microsoft.com/en-us/library/6x627e5f(v=vs.80).aspx),並將分隔符設置爲3個空格 – 2013-05-07 09:27:42

回答

2

的VBA Split()功能可能會有所簡化你的東西。它使用分隔符分割一個字符串,並將這些元素放入一個數組中。例如,下面的測試代碼...

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 

...打印這在VBA IDE的立即窗口:

ST/X 
1000.0000000000000000 
1400.0000000000000000 
40.0000000000000000 
25.0000000000000000 
12.0000000000000000 
[done]