【问题标题】:How to fetch particular key value from text file into excel如何从文本文件中获取特定的键值到excel中
【发布时间】:2016-11-14 13:08:24
【问题描述】:

我需要将文本文件中的字符串提取到 Excel 工作表中。 我只能在 excel(A1) 中获取字符串和粘贴的第一次出现。 现在我需要继续获取直到 EOF 并将该字符串粘贴到 A2,A3,A4....

示例:

文本文件在文本文件中多次包含 xxx=100 键值。 xxx 是常量,而 value 每次都在变化。 所以我需要从文本文件中获取所有 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

【问题讨论】:

  • 显示您目前拥有的代码。查看您的代码很容易提供缺少的指南
  • @KazimierzJawor 先生,我已经用代码更新了我的帖子

标签: vba excel vbscript macros


【解决方案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

【讨论】:

  • 我不知道你的文本文件中有什么,以及为什么你建议使用text = text & textline,这可能是多余的。请改用text = textLine
【解决方案2】:

试试这个:

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

【讨论】:

  • @virajshirsat,你通过了吗?
猜你喜欢
  • 1970-01-01
  • 2019-08-21
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多