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?
Printable View
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?
How about
Code: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
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?
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
Code: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,
Slight mod:
Selection.Range = Split(strData, Chr(13) & Chr(10))(6) '*** :-)