How to read a single row txt file in VBA?

1

I would like to read a txt file through VBA.

All the codes I found on the internet loop in the file (to get all the lines I suppose), but I wanted to just get the first line in a simpler way and put it in a variable.

Here is my current code, which takes the text but I do not think it's legal:

Dim conexao As String

Dim ReadData As String

Open "C:\Sistema\Conexao.txt" For Input As #1

Do Until EOF(1)
   Line Input #1, ReadData
   conexao = ReadData
If Not Left(ReadData, 1) = "*" Then
End If

Loop

Close #1
    
asked by anonymous 14.09.2017 / 00:24

2 answers

1

The best I could get was as follows:

Sub Buscar_Primeira_Linha()

Dim LINHA As Integer

    ' Configura o número da linha que deseja
    LINHA = 1 ' Primeira Linha, por exemplo

    Ler_Arquivo "C:\Arquivo.txt", LINHA

End Sub

I believe that this works ... follow the Ler_Arquivo function:

Function Ler_Arquivo(ByRef ARQUIVO As String, _
                 Optional ByRef LINHA As Integer) As String

Dim COUNT As Integer

    With CreateObject("Scripting.FileSystemObject").OpenTextFile(ARQUIVO)

        If LINHA < 1 Then LINHA = 1
        COUNT = 1

        Do While Not .AtEndOfStream

            If COUNT = LINHA Then
                Ler_Arquivo = .ReadLine
                Exit Do
            Else
                .SkipLine
            End If
            COUNT = COUNT + 1
        Loop
       .Close
    End With

End Function

I hope I have helped!

    
17.09.2017 / 05:14
0

To read only the first line, do not use the Do cycle.

However, it seems to me that this code does some validation to look for the first line (or not) started by "*" . And this being the case, the cycle is needed.

    
04.10.2017 / 10:09