Tested in Excel 365 (16.8730.2046) 64-bit
An easier way to use Open.
- Public Enum ENM_FileOpenType
- FileRead
- FileAppend
- FileOverwrite
- FileRandom
- FileBinary
- End Enum
- '
- Function OpenTextFile(FilePathAndName As String, _
- OpenType As ENM_FileOpenType, Optional TextToWrite)
- Dim f
- Dim strFile
- f = FreeFile
- strFile = ""
- Select Case OpenType
- Case FileRead
- Open FilePathAndName For Input As #f
- ' read whole file into variable
- strFile = Input(LOF(f), #f)
- Case FileAppend
- Open FilePathAndName For Append As #f
- ' read whole file into variable
- Print #f, TextToWrite
- Case FileOverwrite
- Open FilePathAndName For Output As #f
- ' write test to file
- Print #f, TextToWrite
- Case FileRandom
- ' change as needed
- Open FilePathAndName For Random As #f Len = 1000
- ' do stuff
- Case FileBinary
- ' change as needed
- Open FilePathAndName For Binary Access Read Lock Read As #f
- ' do stuff
- End Select
- Close f
- OpenTextFile = strFile
- End Function
- '
- Sub main()
- Dim a
- a = OpenTextFile("C:\temp\mytest.txt", FileAppend, "something")
- a = OpenTextFile("C:\temp\mytest.txt", FileOverwrite, "something new")
- a = OpenTextFile("C:\temp\mytest.txt", FileRead)
- Debug.Print a
- End Sub