Error 54, “Bad file mode”, means a statement tried to use a file in a way its open mode forbids. A file opened For Input cannot be written to, a file opened For Output cannot be read, and random-access statements do not work on sequential files. The statement and the Open disagree, and error 54 is VBA enforcing the disagreement. It is always a code bug, usually a mode chosen by habit rather than by what the code actually does with the file.
Append cannot read either; a file that is both written and read in one session belongs in Random or Binary mode, or must be closed and reopened between phases.Open path For Output As #fn ' write-only: Input #fn here is error 54 Print #fn, "header" Close #fn Open path For Input As #fn ' close and reopen to change direction Line Input #fn, firstLine
For Append because most callers append will hand error 54 to the one caller that reads. Make the mode a parameter with an honest default.If the mode looks right, check that the file number variable still refers to the file you think it does: a reused number after an earlier Close and Open in another procedure silently retargets every statement. Log the number and mode together at the Open and at the failure.
Which modes allow both reading and writing? Random and Binary. Sequential modes are one-directional: Input reads, Output and Append write. Switching direction on a sequential file requires closing and reopening it in the other mode.
Can error 54 be caused by the file itself? No. The file's contents are irrelevant; error 54 is about the mismatch between the open mode and the statement. It fires before any data is touched.