PDA

View Full Version : insert a specific line from a .txt file into word



vkhu
11-25-2017, 09:07 PM
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?

gmayor
11-25-2017, 10:25 PM
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

vkhu
11-25-2017, 10:52 PM
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?

gmayor
11-27-2017, 01:33 AM
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

gmaxey
11-27-2017, 05:58 AM
Graham,

Slight mod:

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