PDA

View Full Version : Writing/Reading integer from text file



linea
07-04-2013, 02:56 AM
Hi!

I'm trying to write a macro to do a very simple thing- simply to read an integer from a text file, then paste that integer, highlighted red, into the document from an external text file, then increment the number in the text file by 1 so that the next time I use the macro it will paste the next integer.

I am getting a "Bad file Mode" (mode 54) error on the line "stream.Write i" - I am sure I'm making some very basic error but I don't really do this stuff at all so if someone could tell me where I'm going wrong I'd be very grateful!



Sub RedInteger()
Dim r As Range
Dim fso As FileSystemObject
Set fso = New FileSystemObject
Dim stream As TextStream
' Create a TextStream.
Set stream = fso.OpenTextFile("C:\Users\thene_000\Dropbox\value.log")
Dim i As Integer
i = Val(stream.ReadAll())
stream.Close
Set stream = fso.OpenTextFile("C:\Users\thene_000\Dropbox\value.log", ForWriting)
Set r = Selection.Range
r.HighlightColorIndex = wdRed
r.Collapse wdCollapseStart
r.InsertAfter i
i = i + 1
stream.Write i
stream.Close

End Sub

JamesAl
07-08-2013, 03:57 AM
Its because you cant read from a stream opened for writing or appending.