Consulting

Results 1 to 5 of 5

Thread: insert a specific line from a .txt file into word

  1. #1

    insert a specific line from a .txt file into word

    Say I have a .txt file with roughly 20 separate lines in it, and want a macro that only insert line #7 at cursor position. Is there a way to do that?
    Last edited by vkhu; 11-25-2017 at 09:22 PM.

  2. #2
    How about

    Sub GetLineSeven()
    Dim strFilename As String
    Dim strTextLine As String
    Dim iFile As Integer: iFile = FreeFile
    Dim iLine As Integer
    
        On Error GoTo lbl_Exit
    
        strFilename = "C:\path\filename1.txt"
    
        Open strFilename For Input As #iFile
        iLine = 0
        Do Until EOF(1)
            iLine = iLine + 1
            Line Input #1, strTextLine
            If iLine = 7 Then
                Exit Do
            End If
        Loop
        Close #iFile
        Selection.Text = strTextLine
    lbl_Exit:
        Exit Sub
    End Sub
    Graham Mayor - MS MVP (Word) 2002-2019
    Visit my web site for more programming tips and ready made processes
    http://www.gmayor.com

  3. #3
    I tested the code but the texts came out wrong. It seem unicode characters can't be read properly ("thời gian" became "thời gian"). I saved the txt file with unicode encoding but that didn't help. Is there any way to get around this issue?

  4. #4
    You didn't mention unicode, for as you have now discovered this method doesn't work with unicode text. The following should work with a text file saved as Unicode

    Sub GetLineSeven()
    Dim objStream As Object
    Dim strData As String
        Set objStream = CreateObject("ADODB.Stream")
        objStream.Charset = "UNICODE"
        objStream.Open
        objStream.LoadFromFile ("C:\path\filename1.txt")
        strData = objStream.ReadText()
        Selection.Range = Split(strData, Chr(13))(6)
        objStream.Close
    lbl_Exit:
        Set objStream = Nothing
        Exit Sub
    End Sub
    Graham Mayor - MS MVP (Word) 2002-2019
    Visit my web site for more programming tips and ready made processes
    http://www.gmayor.com

  5. #5
    Microsoft Word MVP 2003-2009 VBAX Guru gmaxey's Avatar
    Joined
    Sep 2005
    Posts
    3,340
    Location
    Graham,

    Slight mod:

    Selection.Range = Split(strData, Chr(13) & Chr(10))(6) '*** :-)
    Greg

    Visit my website: http://gregmaxey.com

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •