将数据从文本文件提取到Excel

时间:2019-03-08 07:18:52

标签: excel vba

我目前正在从事数据提取项目。该程序将提示用户输入他们要提取的文本文件的数量。之后,用户将选择他们想要的文件。但是,提取的数据仅基于所选的第一个文本文件。我该如何解决这个问题。

Private Sub CommandButton1_Click()
    Dim fileStringBasic As String
    Dim i As Integer
    Dim k As Integer
    Dim iFile As Integer: iFile = FreeFile
    k = InputBox("Give me some input")

    For i = 1 To k
        fileStringBasic = Application.GetOpenFilename()

        If fileStringBasic <> "False" Then
            Open fileStringBasic For Input As #iFile
            Do Until EOF(iFile)
                Line Input #iFile, textline
                Text = Text & textline
            Loop

            Close #iFile
            pos1 = InStr(Text, "Datalog report")
            pos2 = InStr(Text, "BOARD PN")
            pos3 = InStr(Text, "BOARD SN")
            pos4 = InStr(Text, "TESTER")
            pos5 = InStr(Text, "DEVICE")
            pos6 = InStr(Text, "USER NAME")
            Range("A" & ActiveCell.Row).Value = Mid(Text, pos1 + 18, 11)
            Range("B" & ActiveCell.Row).Value = Mid(Text, pos2 + 18, 10)
            Range("D" & ActiveCell.Row).Value = Mid(Text, pos3 + 18, 8)
            Range("E" & ActiveCell.Row).Value = Mid(Text, pos4 + 18, 9)
            Range("F" & ActiveCell.Row).Value = Mid(Text, pos5 + 18, 11)
            Range("H" & ActiveCell.Row).Value = Mid(Text, pos6 + 18, 11)
        End If
        Selection.Offset(1, 0).Select
    Next i
End Sub

1 个答案:

答案 0 :(得分:1)

您必须在循环开始时清除变量文本

For i = 1 To k
    Text = ""
    fileStringBasic = Application.GetOpenFilename()