VBA保存文本文件

Sub 保存文本文件()
Dim sfname As String
sfname = Application.InputBox(prompt:="请输入文本文件的名称", _
Title:="输入文件名称", Type:=2)
If afname = "False" Or sfname = "" Then Exit Sub
sfname = ThisWorkbook.Path & "\" & sfname & ".txt"
On Error Resume Next
If Len(Dir(sfname, vbDirectory)) > 0 Then
    If MsgBox("该文件已经存在,是否删除?", vbQuestion + vbYesNo) = vbYes Then
        Kill sfname
    Else
        Exit Sub
    End If
End If
On Error GoTo 0
Set ws1 = Worksheets("Sheet1")
ActiveWorkbook.SaveAs Filename:=sfname, FileFormat:=xlCSV
MsgBox "保存成功!"
ActiveWorkbook.Close savechanges:=False
End Sub

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要在VBA中在文本文件中间插入行,你可以使用FileSystemObject对象来读取和写入文件。下面是一个示例代码,演示如何在文本文件指定行之后插入新行: ```vba Sub InsertLineInFile() Dim filePath As String Dim lineToInsert As String Dim lineToFind As String Dim tempFilePath As String Dim tempFileName As String ' 设置文件路径 filePath = "C:\path\to\your\file.txt" ' 设置要插入的行 lineToInsert = "This is the new line to insert" ' 设置要找到的行 lineToFind = "This is the line after which you want to insert the new line" ' 创建FileSystemObject对象 Dim fso As Object Set fso = CreateObject("Scripting.FileSystemObject") ' 检查文件是否存在 If Not fso.FileExists(filePath) Then MsgBox "文件不存在!" Exit Sub End If ' 创建一个临时文件保存修改后的内容 tempFilePath = fso.GetParentFolderName(filePath) tempFileName = fso.GetBaseName(filePath) & "_temp" & fso.GetExtensionName(filePath) ' 打开原始文件和临时文件 Dim originalFile As Object Set originalFile = fso.OpenTextFile(filePath, 1) ' 1 表示只读模式 Dim tempFile As Object Set tempFile = fso.CreateTextFile(tempFilePath & "\" & tempFileName, True) ' True 表示创建新文件 ' 逐行读取原始文件并写入临时文件 Do Until originalFile.AtEndOfStream Dim line As String line = originalFile.ReadLine ' 找到要插入行的位置 If line = lineToFind Then ' 在找到的行之后插入新行 tempFile.WriteLine line tempFile.WriteLine lineToInsert Else ' 其他行直接写入临时文件 tempFile.WriteLine line End If Loop ' 关闭文件 originalFile.Close tempFile.Close ' 删除原始文件并重命名临时文件为原始文件名 fso.DeleteFile filePath fso.MoveFile tempFilePath & "\" & tempFileName, filePath MsgBox "新行已成功插入文件!" End Sub ``` 请确保将上述代码中的`filePath`、`lineToInsert`和`lineToFind`替换为你实际的文件路径、要插入的行和要找到的行。 此代码将在指定行之后插入新行,并将修改后的内容保存回原始文件中。请注意,在处理大型文件时,此方法可能会对性能产生一些影响。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

豪情云天

您的鼓励就是创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值