需要从文本文件中将特定字符串提取到Excel工作表中

时间:2016-11-16 14:30:17

标签: excel vba excel-vba macros

我需要从文本文件中找到一个键值对并将其粘贴到Excel列

在文件末尾有多次出现键值对

  • Key =响应代码是常量
  • 值=每次不变化

示例:

文字档案:

Username : admin 
Old password : qqqq
New password : 1111
Security question : 1
Security answer : Mom

Response Code: -500

Operation Completed

Response Code: -100
....
Response Code: -202
....
....

我的代码:

    Dim myFile As String
    Dim text As String
    Dim textline As String
    Dim x 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
    x = InStr(text, "Response code")
    Range("A1").Value = Mid(text, x + 15, 3)

注意:我只是第一次出现,即响应代码:-500 我想要找到所有出现到文件结尾的循环并将该内容粘贴到Excel工作表列A1中。

1 个答案:

答案 0 :(得分:1)

代码的小mod:

Sub dural()
    Dim myFile As String
    Dim text As String
    Dim textline As String
    Dim i As Long

    myFile = "C:\TestFolder\test.log"
    Close #1
    Open myFile For Input As #1

    i = 1
    Do Until EOF(1)
        Line Input #1, textline
        If InStr(textline, "Response Code:-") > 0 Then
            Cells(i, 1).Value = Replace(textline, "Response Code:-", "")
            i = i + 1
        End If
    Loop
    Close #1
End Sub

产生

enter image description here

相关问题