首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用VBA创建和写入txt文件

如何使用VBA创建和写入txt文件
EN

Stack Overflow用户
提问于 2012-07-16 19:20:20
回答 5查看 564.7K关注 0票数 127

我有一个基于输入手动添加或修改的文件。由于该文件中的大多数内容都是重复的,只有十六进制值在变化,所以我想让它成为一个工具生成的文件。

我想写c代码,这些代码将被打印到那个.txt文件中。

使用VBA创建.txt文件的命令是什么?如何对其进行写入

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2018-04-05 22:16:20

详述Ben's answer

如果您添加了对Microsoft Scripting Runtime的引用并正确输入了变量fso,您就可以利用自动补全 (Intellisense)并发现FileSystemObject的其他强大功能。

下面是一个完整的示例模块:

代码语言:javascript
复制
Option Explicit

' Go to Tools -> References... and check "Microsoft Scripting Runtime" to be able to use
' the FileSystemObject which has many useful features for handling files and folders
Public Sub SaveTextToFile()

    Dim filePath As String
    filePath = "C:\temp\MyTestFile.txt"

    ' The advantage of correctly typing fso as FileSystemObject is to make autocompletion
    ' (Intellisense) work, which helps you avoid typos and lets you discover other useful
    ' methods of the FileSystemObject
    Dim fso As FileSystemObject
    Set fso = New FileSystemObject
    Dim fileStream As TextStream

    ' Here the actual file is created and opened for write access
    Set fileStream = fso.CreateTextFile(filePath)

    ' Write something to the file
    fileStream.WriteLine "something"

    ' Close it, so it is not locked anymore
    fileStream.Close

    ' Here is another great method of the FileSystemObject that checks if a file exists
    If fso.FileExists(filePath) Then
        MsgBox "Yay! The file was created! :D"
    End If

    ' Explicitly setting objects to Nothing should not be necessary in most cases, but if
    ' you're writing macros for Microsoft Access, you may want to uncomment the following
    ' two lines (see https://stackoverflow.com/a/517202/2822719 for details):
    'Set fileStream = Nothing
    'Set fso = Nothing

End Sub
票数 56
EN

Stack Overflow用户

发布于 2012-07-16 19:27:12

使用FSO创建文件并对其进行写入。

代码语言:javascript
复制
Dim fso as Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile as Object
Set oFile = FSO.CreateTextFile(strPath)
oFile.WriteLine "test" 
oFile.Close
Set fso = Nothing
Set oFile = Nothing    

请参阅此处的文档:

票数 181
EN

Stack Overflow用户

发布于 2017-10-27 04:25:26

代码语言:javascript
复制
Open ThisWorkbook.Path & "\template.txt" For Output As #1
Print #1, strContent
Close #1

更多信息:

  • Microsoft支持Microsoft文档:
  • Microsoft文档:
  • Microsoft文档:
  • Office支持:
票数 65
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11503174

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档