2016-11-14 63 views
-2

我需要从文本文件中取出字符串到Excel表格中。 我能够在excel(A1)中仅获取字符串ans贴的第一次出现。 现在我需要继续提取,直至EOF并粘贴到A2,A3,A4是弦....如何从文本文件中取出特定的键值到excel中

例子:

一个文本文件包含XXX = 100键值多个文本文件的时间。 xxx是恒定的,而值每次都在变化。 所以我需要从文本文件中获取所有xxx值,并将其粘贴到每个单独的excel单元格中。

我的代码:

Private Sub CommandButton1_Click() 

Dim myFile As String, text As String, textline As String, posLat As Integer, posLong As Integer 

myFile = "C:\test\test.log" 

Open myFile For Input As #1 

Do Until EOF(1) 

Line Input #1, textline 

text = text & textline 

Loop 

Close #1 

posLat = InStr(text, "Response Code") 

Range("A1").Value = Mid(text, posLat + 15, 3) 

End Sub 
+2

告诉你到目前为止的代码。看到您的代码很容易提供缺少的指导 –

+0

@KazimierzJawor先生我已更新我的帖子,代码 –

回答

1

尝试用这种改进代码:

Private Sub CommandButton1_Click() 

Dim myFile As String, text As String, textline As String, posLat As Integer, posLong As Integer 
Dim I as long 

myFile = "C:\test\test.log" 

Open myFile For Input As #1 

Do Until EOF(1) 

Line Input #1, textline 

'text = text & textline 
text = textLine 

posLat = InStr(text, "Response Code") 

Range("A1").Offset(I,0).Value = Mid(text, posLat + 15, 3) 
I= I+1 

Loop 

Close #1 


End Sub 
+0

它不起作用,打印相同的值,直到EOF。 –

+0

我不知道你里面有什么文本文件,为什么你建议使用'text = text&textline'这可能是多余的。改用'text = textLine'来代替。 –

1

试试这个:

Option Explicit 

Sub main() 
    Dim myFile As String 
    Dim valsArray As Variant 
    Dim text As String, vals As String 
    Dim iVal As Long 

    myFile = "C:\test\test.log" 

    Open myFile For Input As #1 
    text = Input$(LOF(1), #1) '<--| read all file in a string 
    Close #1 

    valsArray = Split(text, "Response Code=") '<--| split text file into bits separated by "Response Code=" string 
    For iVal = 1 To UBound(valsArray) '<--| loop through generated array skipping its first element 
     vals = vals & Left(valsArray(iVal), 3) & "," '<--| build values string delimited by a comma 
    Next iVal 
    valsArray = Split(Left(vals, Len(vals) - 1), ",") '<--| split values string into an array 
    Range("A1").Resize(UBound(valsArray) + 1).Value = Application.Transpose(valsArray) '<--| write down the array 
End Sub 
+0

@virajshirsat,你通过它吗? – user3598756

相关问题