How to read a single-line txt file in VBA?

Asked

Viewed 2,872 times

1

I would like to read a txt file through VBA.

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

Here’s my current code, which picks up the text but I’m not finding it cool:

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

2 answers

1


The best I could get was this way:

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 it works... follows the function Ler_Arquivo:

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’ve helped!

0

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.