PDA

View Full Version : Solved: Writing data from workbook to text file



xena2305
05-26-2012, 04:26 PM
Hi,
I have an excel sheet with one colum and many rows that filled with long deciaml numbers(positive and negetive).
I need to write all these numbers into a txt file with the following terms:
1. the decimal numbers must be shorten to 6 digits after the point.
2. the numbers must come one after the other with a ";" between them
not in lines as thay appear in the workbook.

in the following code i used round function to define the numbers of decimal places but the problom that it drops sometimes the first digit in the number,
for example "0.123456789" i see as ".123456".
i also dont know how to combine them into one line with a sepeprator.

Public Sub save_to_txt()
Close #1
Open "D:\WRITE_TEST.txt" For Output As #1
Dim RowIndex As Integer
Dim cellsvalue As Double
RowIndex = 1

While IsEmpty(Cells(RowIndex, 3)) = 0
cellsvalue = Round(Cells(RowIndex, 3), 6)
Write #1, cellsvalue
RowIndex = RowIndex + 1
Wend
Close #1
End Sub

Opv
05-26-2012, 05:30 PM
The following works for me if all you want is a single string with comma-separated values. You will need to change the data range to suit your needs.


Sub save_to_txt()

Dim dataRng As Range, i As Long, output As String

'Change the range to suit your needs
Set rng = Sheets(1).Range("A1:A10")

Close #1

Open "DWRITE_TEST.txt" For Output As #1

For i = 1 To rng.Count

output = output & Round(rng(i).Value, 6) & ", "

Next

output = Left(output, Len(output) - 2)

Write #1, output

Close #1

End Sub

Opv
05-26-2012, 07:14 PM
Here's the corrected code. I noticed that I left an error in the path statement when I changed the path from the test path I was using back to your path. Sorry about that.


Sub save_to_txt()

Dim dataRng As Range, i As Long, output As String

'Change the range to suit your needs
Set rng = Sheets(1).Range("A1:A10")

Close #1

Open "D:\WRITE_TEST.txt" For Output As #1

For i = 1 To rng.Count

output = output & Round(rng(i).Value, 6) & ", "

Next

output = Left(output, Len(output) - 2)

Write #1, output

Close #1

End Sub

shrivallabha
05-26-2012, 09:37 PM
Try:
Print #1, cellsvalue
instead of:
Write #1, cellsvalue
for the code posted at #1.

xena2305
05-27-2012, 12:34 AM
thanks for the help.