使用 VBA 创建文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41120832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 11:41:54  来源:igfitidea点击:

Create Text File using VBA

excelvba

提问by GAURAV CHHABRA

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

I am getting the Error below:

我收到以下错误:

Compiler Error: Expected : expression

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

Tried lot many things but not working

尝试了很多东西但不起作用

采纳答案by KyloRen

Try this code, it will create the object for you and you can add data to the file as you need and then save it.

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

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

回答by Andrew Truckle

There is another way you can do it:

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

Dim hFile As Long

hFile = FreeFile

Open strFile For Output As #hFile

Print #hFile, "Line of text"

Close #hFile

This way you avoid needed to use the FileSystemObject.

这样您就可以避免需要使用FileSystemObject.