VBA Tip - Acessando arquivo Texto - Text File access - Scripting Runtime object library - Scrrun.dll


É possível usar o Scripting Runtime object library para manipular arquivos texto. O exemplo abaixo assume que seu projeto VBA acrescentou uma referência à biblioteca Microsoft Scripting Runtime

Sub WriteToTextFile()
Dim fs As Scripting.FileSystemObject, f As Scripting.TextStream
Dim l As Long
    Set fs = New FileSystemObject
    Set f = fs.OpenTextFile("C:\FolderName\TextFileName.txt", _
        ForWriting, True)
    With f
        For l = 1 To 100
            .WriteLine "This is line number " & l
        Next l
        .Close
    End With
    Set f = Nothing
    Set fs = Nothing
End Sub

Sub AppendToTextFile()
Dim fs As Scripting.FileSystemObject, f As Scripting.TextStream
Dim l As Long
    Set fs = New FileSystemObject
    Set f = fs.OpenTextFile("C:\FolderName\TextFileName.txt", _
        ForAppending, True)
    With f
        For l = 1 To 100
            .WriteLine "Added line number " & l
        Next l
        .Close
    End With
    Set f = Nothing
    Set fs = Nothing
End Sub

Sub ReadFromTextFile()
Dim fs As Scripting.FileSystemObject, f As Scripting.TextStream
Dim l As Long
    Set fs = New FileSystemObject
    Set f = fs.OpenTextFile("C:\FolderName\TextFileName.txt", _
        ForReading, False)
    With f
        l = 0
        While Not .AtEndOfStream
            l = l + 1
            Cells(l, 5).Formula = .ReadLine
        Wend
        .Close
    End With
    Set f = Nothing
    Set fs = Nothing
End Sub


Tags: VBA, Tips, files, directory, folder, Scripting Runtime object library, Scrrun.dll, FileSystemObject, GetFiles, ChangeFileAttributes, 





Nenhum comentário:

Postar um comentário

diHITT - Notícias