Home » excel » excel vba – Insert top x rows from text with VBA

excel vba – Insert top x rows from text with VBA

Posted by: admin May 14, 2020 Leave a comment


I want to insert the top x rows from a text file. I can give the number of the StartRow, but is there such parameters where I can give the “EndRow” number to give the top x rows what I want to inseret.

Sub insertTopX()

    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Users\HarrsionDavid\Desktop\AnswerForEveryQuestions" _
        .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
How to&Answers:

You can read the txt file and split it by new line. Then you would have an array which can be easy to work with.

Sample file:

enter image description here

  • Read the file and parse it to a variant;
  • Pass the startRow and the endRow;

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

This is the result:

enter image description here

This is the 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

    Close #fileNo

End Function