如何使用 VBA 创建和写入 txt 文件 [英] How to create and write to a txt file using VBA

查看:804
本文介绍了如何使用 VBA 创建和写入 txt 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个根据输入手动添加或修改的文件.由于该文件中的大部分内容都是重复的,只有十六进制值发生了变化,我想将其设为工具生成的文件.

I have a file which is manually added or modified based on the inputs. Since most of the contents are repetitive in that file, only the hex values are changing, I want to make it a tool generated file.

我想编写将要打印在 .txt 文件中的 c 代码.

I want to write the c codes which are going to be printed in that .txt file.

使用 VBA 创建 .txt 文件的命令是什么,我该如何写入

What is the command to create a .txt file using VBA, and how do I write to it

推荐答案

详细说明 Ben 的回答:

如果您添加对 Microsoft Scripting Runtime 的引用并正确键入变量 fso,您可以利用自动完成功能(智能感知)并发现FileSystemObject 的其他强大功能.

If you add a reference to Microsoft Scripting Runtime and correctly type the variable fso you can take advantage of autocompletion (Intellisense) and discover the other great features of FileSystemObject.

这是一个完整的示例模块:

Here is a complete example module:

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

这篇关于如何使用 VBA 创建和写入 txt 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆