Nytro
Nytro

Reputation: 143

How to write to text file after creating it?

I want to extract cell A2 from Excel and its offset (0,1) and put it in a created text file.

How to proceed, since I haven't declared a variable for the created text file?

Sub CreateFileandWrite()
Open ThisWorkbook.Path & "\Test.txt" For Output As #1
Print #1, "Hello"
Print #1, strContent
Close #1
End Sub

Upvotes: 0

Views: 220

Answers (2)

byte me
byte me

Reputation: 766

If you want to create the txt file with the code you can also do it this way

Public Sub txtfile()

    Dim filePath As String
    Dim fso As FileSystemObject
    Set fso = New FileSystemObject
    Dim fileStream As TextStream

    filePath = "C:\Users\Nytro\Desktop"

    Set fileStream = fso.CreateTextFile(filePath & "\" & "NameOfFile" & ".txt")

    Set cell = Cells(2, 1)
    Set cell2 = cell.Offset(0, 1)

    fileStream.WriteLine cell 'or fileStream.WriteLine cell & cell2 if you want to write them on the same line
    fileStream.WriteLine cell2

End Sub

Upvotes: 2

Gary's Student
Gary's Student

Reputation: 96753

For A2 and its offset:

Sub FileMaker()

    Close #1
    Open "C:\TestFolder\sample1.txt" For Output As #1
        Print #1, Range("A2").Value
        Print #1, Range("B2").Value
    Close #1
End Sub

Upvotes: 2

Related Questions