How can I write to a text file reliably from Excel VBA?

前端 未结 4 1832
心在旅途
心在旅途 2021-01-11 10:31

I\'m trying to use Excel VBA to write to a text file. I\'m doing a few of these:

MyFile1 = \"C:\\outputFromExcel1.txt\"
fnum1 = FreeFile()
Open MyFile1 For          


        
相关标签:
4条回答
  • 2021-01-11 11:04

    Yes, you should be closing the files with the Close method. I'm not sure if that's what causing the problems but you should be doing that either way.

    If you're doing a lot of filehandling in your VBA code it might be worth looking at using FSO (FileSystemObject), I think it was originally for letting VBScript do file processing, but I prefer it to both VB6s and VBAs built in file handling. See here for more details (and there's a big sample showing off how to do most things you need in one of those pages as well).

    0 讨论(0)
  • 2021-01-11 11:07

    Have you considered writing the text to a different sheet (or a different workbook) and then using:

    ActiveWorkbook.SaveAs Filename:="C:\MyFile.txt", FileFormat:=xlText
    

    Not sure if this would give you better results (in terms of performance and/or formatting), but perhaps worth a try.

    0 讨论(0)
  • 2021-01-11 11:18

    Just a necro solution: I have found the Close #1 method to still leave a truncated file. Instead, or in addition to, use the Application.Quit for Excel to close Excel. This flushes the cache and completes the write to the text file.

    0 讨论(0)
  • 2021-01-11 11:22

    You can use Close #fnum1 to close the file handle and it should flush the remaining buffer contents.

    0 讨论(0)
提交回复
热议问题