繁体   English   中英

连接文本文件中的行-Excel VBA

[英]Concatenating lines from text file - Excel VBA

我有一个像这样的格式的文本文件,

文本:

-- Begin 
  Line1
  Line2
  Line3
      ^
-- Begin
  Line1
  Line2
  Line3
  Line4
      ^
.
.
.
.

我基本上想将Line1放到Line(whatever)之间的Line(whatever) --Begin到数组中的^ ,所以数组中的每个元素都是一串线

Array =  [("Line1"  & vbNewLine & "Line 2") , ("Line1"  & vbNewLine & "Line 2" & vbNewLine & "Line 3") ... ]

但基本上是想将数组中的每个元素存储在一个单元格中。 (可能甚至不需要使用数组)...

不知道在excel VBA中这是否可能,但这是我到目前为止已经尝试过的方法

    Dim FileNum As Integer
    Dim DataLine As String
    Dim Lines As Variant
    Dim j As Integer


    FileNum = FreeFile()
    Open "C:..." For Input As #FileNum


 While Not EOF(FileNum)
       Line Input #FileNum, DataLine

      If InStr(DataLine, "-- Begin") > 0 Then
        nextLinecounter = 1

      ElseIf InStr(DataLine, "^") > 0 Then
        nextLinecounter = 0
        j = j + 1

      ElseIf nextLinecounter = 1 Then
       Lines(j) = DataLine + .. Somehow concatenate next lines into array

     End If


Wend

我被困在如何跳过下一行并将其附加到当前条目的方式上,谢谢。

所以我会做一些不同的事情。 使用最新的方法进行文件读取。

在VBA中查看有关如何读取* .txt文件的更多详细信息- here

注意:您需要通过VBE->工具->引用添加对Microsoft Scripting Runtime引用

Option Explicit

Sub ReadTxtFile()

    Dim oFSO As New FileSystemObject
    Dim oFS As TextStream

    Dim filePath As String
    filePath = "C:\Users\" & Environ$("username") & "\Desktop\foo.txt"

    If Not fileExist(filePath) Then GoTo FileDoesntExist

    On Error GoTo Err

    ReDim arr(0) As String
    Dim s As String

    Set oFS = oFSO.OpenTextFile(filePath)
    Do While Not oFS.AtEndOfStream
        Dim line As String
        line = oFS.ReadLine
        If InStr(line, "-- Begin") = 0 And InStr(line, "^") = 0 Then
            s = s & line
        End If
        If InStr(line, "^") > 0 Then
            arr(UBound(arr)) = s
            ReDim Preserve arr(UBound(arr) + 1)
            s = vbNullString
        End If
    Loop
    ReDim Preserve arr(UBound(arr) - 1)
    oFS.Close

    Dim k As Long
    For k = LBound(arr) To UBound(arr)
        Debug.Print k, arr(k)
    Next k
    Exit Sub

FileDoesntExist:
    MsgBox "File Doesn't Exist", vbCritical, "File not found!"
    Exit Sub

Err:
    MsgBox "Error while reading the file.", vbCritical, vbNullString
    oFS.Close
    Exit Sub

End Sub


Function fileExist(path As String) As Boolean
    fileExist = IIf(Dir(path) <> vbNullString, True, False)
End Function

foo.txt看起来像这样

-- Begin 
  Line1
  Line2
  Line3
      ^
-- Begin
  Line1
  Line2
  Line3
  Line4
      ^

你的数组看起来像这样

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM