PDA

View Full Version : Write from excel to text file format



marissaliana
05-08-2017, 07:14 AM
Hi,

I want to store some values from an excel file to a txt file.

I use this code and it works fine


Sub saveText2() Dim filename As String, lineText As String
Dim myrng As Range, i, j

filename = ThisWorkbook.Path & "\textfile-" & Format(Now, "ddmmyy-hhmmss") & ".txt"

Open filename For Output As #1

Set myrng = Range("tblFields")

For i = 1 To myrng.Rows.count
For j = 1 To myrng.Columns.count


lineText = IIf(j = 1, " ", lineText & " ") & myrng.Cells(i, j)

Next j
Print #1, lineText
Next i

Close #1
End Sub

I just have one problem. In the excel, the values are floats. When I transfer them to the txt file, then the zeros are dissapeared from the decimals. I need to transfer the values, exactly the same format as in the excel. Is it possible?

Thank you

Fennek
05-08-2017, 07:38 AM
Hi,

try it with

lineText = IIf(j = 1, " ", lineText & " ") & myrng.Cells(i, j).Text

regards

marissaliana
05-08-2017, 07:44 AM
It worked fine!!! Than you!!!

HARSH
11-28-2018, 10:53 PM
When I use above code to copy Excel data into text file (.txt) , I see cursor move to blank line. I want cursor to be remain at the end of line
e.g: if we have 3 rows cursor should stay at end of 3rd line. or can we do the backspace after printing the line so that cursor will go back.