VBA - Read a file. TXT and manipulate its lines

Asked

Viewed 3,166 times

1

I’m trying to make a Query generator using Excel (VBA), but I’m not able to manipulate some data inside a file . sql.

Ex.:

Select *
From Tabela t
Where t.id = 1
<PROP>

Every time he finds a line that is written PROP he must exchange it for the value that is in cell H3, and at the end save the file.

I can already make him read the file until the end, but I don’t know how to change the PROP value by the value that is in cell H3.

To be explained better.

Dim strTextLine
Dim strTextFile
Dim intFileNumber

'Nome completo do arquivo a ser aberto
strTextFile = "C:\Users\Desktop\Query.sql"

'Criar numeração
intFileNumber = 1

'Criar conexão com o arquivo txt
Open strTextFile For Input As #intFileNumber  '<- Input ou Append?

'Loop para percorrer as linhas do arquivo até o seu final
Do While Not EOF(intFileNumber)
   Line Input #intFileNumber, strTextLine
   If (strTextLine = "<PROP>") Then
       'como faço para alterar a tag <PROP> por um valor que está em uma variavel?
       ' Já consegui encontrar a linha só não sei como altero o valor no arquivo.
    End If
Loop

'Fechar a conexão com o arquivo
Close #intFileNumber

Sincerely yours,

2 answers

1

As I still cannot comment, I leave a suggestion that I think can help you.

Columns("B:B").Select
    Selection.Replace What:="PROP", Replacement:=Range("H1").Value, LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

Define the columns where the text has to be located and run the macro.

  • I don’t understand R. Galamba.

1

I am guessing that the . sql file already exists. Adjust the code according to the need.

Option Explicit

Sub SqlMacro()
Dim ficheiro As String
Dim texto As String
Dim textline As String
Dim celula As String

    On Error GoTo Erro

    'localização do ficheiro
    ficheiro = "C:\teste.sql"

    'abre o ficheiro
    Open ficheiro For Input As #1

    'lê o ficheiro
    Do Until EOF(1)
        Line Input #1, textline
        texto = texto & textline
    Loop
    'fecha o ficheiro
    Close #1

    'adquire o conteúdo da célula H3, na folha 1
    celula = Sheets(1).Cells(3, 8)  '(linha, coluna)
    'faz a troca de <PROP> pelo conteúdo da célula
    texto = Replace(texto, "<PROP>", celula)

    'sobrescreve o ficheiro
    Open ficheiro For Output As #1
    Print #1, texto
    Close #1
    Exit Sub

Erro:
    'se houver algum erro, descreve-o
    MsgBox Err.Description
End Sub

Browser other questions tagged

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