使用VBA创build文本文件

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 

我得到下面的错误:

编译器错误:预期:expression式

试了很多东西,但没有工作

试试这个代码,它会为你创build对象,你可以根据需要添加数据到文件,然后保存。

 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 

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

 Dim hFile As Long hFile = FreeFile Open strFile For Output As #hFile Print #hFile, "Line of text" Close #hFile 

这样可以避免使用FileSystemObject