使用VBA创建文本文件

时间:2016-12-13 12:11:30

标签: excel vba

Private Sub Update()

    Dim myFileSystemObject As FileSystemObject
    Dim myFile As Object

    Set myFileSystemObject = New FileSystemObject

    Set myFile = myFileSystemObject.CreateTextFile("C:\Error.txt")

    myFile.WriteLine "Error"

    myFile.Close
    Set myFileSystemObject = Nothing

End Sub

我收到以下错误:

  

编译器错误:预期:表达式

尝试了许多事情但没有工作

2 个答案:

答案 0 :(得分:2)

还有另一种方法可以做到:

Dim hFile As Long

hFile = FreeFile

Open strFile For Output As #hFile

Print #hFile, "Line of text"

Close #hFile

这样您就可以避免使用FileSystemObject

答案 1 :(得分:0)

尝试使用此代码,它将为您创建对象,您可以根据需要将数据添加到文件中,然后保存。

Private Sub Update()

    Dim fSo As Object
    Dim myFile As Object


       Set fSo = CreateObject("Scripting.FileSystemObject")

       Set myFile = fSo.CreateTextFile("c:\sample.txt", True)

       myFile.WriteLine "Error"

    myFile.Close
    Set fSo = Nothing

End Sub