使用VBA从文本插入前x行

时间:2018-06-07 08:17:40

标签: excel-vba text insert vba excel

我想从文本文件中插入前x行。我可以给出StartRow的编号,但是有没有这样的参数,我可以给出" EndRow"数字给出前x行我想要的内容。

Sub insertTopX()

    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Users\HarrsionDavid\Desktop\AnswerForEveryQuestions" _
        ,Destination:=Cells(1,1))
        .Name = "test_file.txt"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileConsecutiveDelimiter = True
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With

End Sub

1 个答案:

答案 0 :(得分:2)

您可以阅读txt文件并按新行拆分。然后你会得到一个易于使用的数组。

示例文件:

enter image description here

  • 阅读文件并将其解析为变体;
  • 传递startRowendRow;
Option Explicit

Public Sub TestMe()

    Dim filePath As String
    filePath = "C:\Users\user\User\nt.txt"

    Dim myFile As String
    myFile = ReadFileLineByLineToString(filePath)

    Dim startRow As Long
    Dim endRow As Long
    Dim fixedFile As Variant

    fixedFile = Split(myFile, vbCrLf)

    startRow = 2
    endRow = 3

    Dim cnt As Long
    For cnt = startRow To endRow
        Debug.Print fixedFile(cnt - 1)
    Next cnt

End Sub

结果如下:

enter image description here

这是ReadFileLineByLineToString

Public Function ReadFileLineByLineToString(path As String) As String

    Dim fileNo As Long
    fileNo = FreeFile

    Open path For Input As #fileNo

    Do While Not EOF(fileNo)
        Dim textRowInput As String
        Line Input #fileNo, textRowInput
        ReadFileLineByLineToString = ReadFileLineByLineToString & textRowInput
        If Not EOF(fileNo) Then
            ReadFileLineByLineToString = ReadFileLineByLineToString & vbCrLf
        End If
    Loop

    Close #fileNo

End Function