2

I am writing a VBA code in an Excel spreadsheet. The code tested OK and now it's time to output the results to an ASCII (text) file - as this has been the very intent of the code since the very beginning. I've done this dozens of times in the past. To make extra sure (memory blanks out sometimes), I google-checked the "Open" command to open a file and associate it to a file number. It all seems alright - and yet the spreadsheet doesn't even create the output file, let alone output something to it. Here's what I'm doing; the Print #1 command was placed as an output text and so far it's the only output-to-file command in the whole code.

Sub Driver()

[... Lines of code ...]

' Open the file for output
Open "WriteADIF.txt" For Output As #1

Print #1, "Hello"

[... Lines of code ...]

Close #1

End Sub

The programs runs fine till the end, no error message is issued and yet no "WriteADIF.txt" file is created. It should find it in the same folder where the Excel sheet is stored, but it is not there. This is so baffling I don't know what to say or do. Could this be some kind of security issue? For example, Excel is not set as a trusted source for writing files to the disk? The folder is not system-protected, it's an ordinary C:\Users... type one.

Any ideas?

3
  • 3
    Use the full path - Open ThisWorkbook.Path & "\WriteADIF.txt" For Output As #1 Commented Nov 5 at 5:07
  • 4
    ...if you just use the filename, the location will default to the current directory, which may be different from where the workbook is saved. Commented Nov 5 at 5:14
  • 2
    Debug.Print CurDir prints the current directory to the Immediate window. Commented Nov 5 at 8:10

1 Answer 1

2

When dealing with files in VBA it's best to always use the full path.

For example if you want to create a file in the same directory as the saved workbook you could use:

Open ThisWorkbook.Path & "\WriteADIF.txt" For Output As #1

assuming your Excel file is on a "regular" local or network drive, and not opened from a HTTP location such as SharePoint or OneDrive.

Otherwise, you risk creating the file somewhere else (in this case in the "current directory")

Sign up to request clarification or add additional context in comments.

3 Comments

Many thanks again for your help. Also, I have just realized that your suggestion - which worked like a charm in a "regular" directory - did not work well when I pointed the output to an OneDrive location. Yet another trick I learned, thanks.
If it's your own onedrive you need to work with there are ways to find the local path - eg see stackoverflow.com/questions/78818217/…
For Onedrive I'd recommend stackoverflow.com/questions/33734706/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.