PDA

View Full Version : [SOLVED:] Writing and Reading the Same Set of Ranges



aerodoc
03-23-2014, 05:04 PM
I have several ranges, that I want to (a) write to a text file and (b) read back in at a later date. The writing part seems pretty easy and goes something like this (comma separated if the range has multiple columns):


Sub Write()

Open "C:\test\test.txt" For Output As #1

Print #1, "Range 1"

For j = 1 To 3
Print #1, Cells(j, 1)
Next j

Print #1, "Range 2"

For j = 10 To 11
Print #1, Cells(j, 2) & "," & Cells(j, 3)
Next j

Close

End Sub

The same cells written out will need to be read back in (so same number of rows and columns for each range). I can do (if useful) anything to the output file. For example, I could put an "A" in the first column of the first set of inputs, a "B" in the first column of the second set of inputs, etc. This may or may not help to read data back in? Basically, I just need to read back in the same set of cells that were written out (and place them in the same position).

The goal is to create a simple way to save the data to an ascii file for various sets of inputs and read them back in later. One thing I did not include, which I am assuming may not be too difficult, is to include a pop up window where you can select the file to write to and read from. The current example is a just a direct path, but would need to be changed later to make it more flexible.

patel
03-24-2014, 12:11 AM
why not save as csv ?

p45cal
03-24-2014, 05:17 AM
check out the Line Input # statement in help. Once you have your line in a variable you can split it with the Split function using a comma as the delimiter, something along these lines:

Sub mRead()
Open "C:\test\test.txt" For Input As #1
Do
Line Input #1, xx
Loop Until xx = "Range 1"
For j = 1 To 3
Line Input #1, xx
Cells(j, 1) = xx
Next j
Do
Line Input #1, xx
Loop Until xx = "Range 2"
For j = 10 To 11
Line Input #1, xx
Cells(j, 2).Resize(, 2) = Split(xx, ",")
Next j
Close
End Sub
If there's any chance at all that the data in any single cell will contain a comma, then I'd use an unusual character such as "¬" as the delimiter.

aerodoc
03-25-2014, 09:20 PM
p45cal,

Thanks, this works great. I did vary it a bit since the code as is will read into the cells as a text string as opposed to a number. There is probably an easier way to do it, but instead of using the resize approach, I used:


Cells(j, 1) = xx(0)
Cells(j, 2) = xx(1)