2

I am trying to create a file and save text into it. I tried below code but when I am using write #1, script will just replace existing text with the new text. I tried write #0 but no luck. Any suggestions.

Sub TestResultFile(output As String)
  Dim myFile As String
  myFile = Application.DefaultFilePath & "TestResults.txt"
  Debug.Print myFile
  Open myFile For Output As #1
  Write #1, output
  Close #1
End Sub

Update:

Answer by Lakshmi helped me solve this issue.

6
  • If you look it up in The Programmers Guide to Visual Basic it says Visual Basic allows you to process drives, folders, and files in two different ways: through traditional methods such as the Open statement, Write#, and so forth, and through a new set of tools, the File System Object (FSO) object model. Commented Mar 12, 2019 at 6:17
  • @Noodles I am not able to use File System Object (FSO) because FSO if for Excel for Windows. Can you please confirm? Commented Mar 12, 2019 at 6:26
  • Try Open myFile For Append As #1 Commented Mar 12, 2019 at 6:33
  • 1
    @meMadhav I mean try to use different file open mode. Instead of For Output use For Append. Then write your output string to the file and it should not replace existing text Commented Mar 12, 2019 at 7:43
  • 1
    @xmojmr Thank you man. For Append resolved my problem. Commented Mar 12, 2019 at 8:18

1 Answer 1

6

User Append to add text to new line.

try below code-

Sub TestResultFile(output As String)
  Dim myFile As String
  myFile = Application.DefaultFilePath & "TestResults.txt"
  Debug.Print myFile
  Open myFile For Append As #1
  Write #1, output
  Close #1
End Sub
Sign up to request clarification or add additional context in comments.

Comments

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.