Open file For

Tested in Excel 365 (16.8730.2046) 64-bit

An easier way to use Open.

 
 
  1. Public Enum ENM_FileOpenType
  2.     FileRead
  3.     FileAppend
  4.     FileOverwrite
  5.     FileRandom
  6.     FileBinary
  7. End Enum
  8. '
  9. Function OpenTextFile(FilePathAndName As String, _
  10.     OpenType As ENM_FileOpenType, Optional TextToWrite)
  11.     Dim f
  12.     Dim strFile
  13.    
  14.     f = FreeFile
  15.     strFile = ""
  16.     Select Case OpenType
  17.         Case FileRead
  18.             Open FilePathAndName For Input As #f
  19.             ' read whole file into variable
  20.            strFile = Input(LOF(f), #f)
  21.         Case FileAppend
  22.             Open FilePathAndName For Append As #f
  23.             ' read whole file into variable
  24.            Print #f, TextToWrite
  25.         Case FileOverwrite
  26.             Open FilePathAndName For Output As #f
  27.             ' write test to file
  28.            Print #f, TextToWrite
  29.         Case FileRandom
  30.             ' change as needed
  31.            Open FilePathAndName For Random As #f Len = 1000
  32.             ' do stuff
  33.        Case FileBinary
  34.             ' change as needed
  35.            Open FilePathAndName For Binary Access Read Lock Read As #f
  36.             ' do stuff
  37.    End Select
  38.     Close f
  39.     OpenTextFile = strFile
  40. End Function
  41. '
  42. Sub main()
  43.     Dim a
  44.    
  45.     a = OpenTextFile("C:\temp\mytest.txt", FileAppend, "something")
  46.     a = OpenTextFile("C:\temp\mytest.txt", FileOverwrite, "something new")
  47.     a = OpenTextFile("C:\temp\mytest.txt", FileRead)
  48.    
  49.     Debug.Print a
  50. End Sub

Add a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.