VBA与Excel入门系列-09-FSO(下篇)-文件操作

VBA与Excel入门系列-09-FSO(下篇)-文件操作

编码文章call10242025-02-25 11:12:2322A+A-
  • 系统环境:Windows 10
  • Excel:2010版本


在操作电脑的过程中,时常伴随着这样的动作:新建文件夹、新建文件、删除文件夹、删除文件等。今天继续FSO,说说对文件的操作



Part 1:文件操作

  • 文件创建,strNewFile为新建文本文件的绝对地址
Set objNewFile= objFSO.CreateTextFile(strNewFile, True)


  • 文件写入(针对文本文件)
Set objNewFile= objFSO.CreateTextFile(strNewFile, True)
objNewFile.writeline ("测试1")
objNewFile.writeline ("测试2")
  • 文件删除
objFSO.GetFile(strNewFile).Delete
  • 文件删除也可以这样写
Kill strNewFile
  • 文件打开(针对文本文件)
Const ForReading = 1, ForWriting = 2, ForAppending = 8, TristateTrue = -1
Set strNewFileOpen = objFSO.OpenTextFile(strNewFile, ForAppending, TristateTrue)

其中Const定义常量,可以直接写成

Set strNewFileOpen = objFSO.OpenTextFile(strNewFile, 8, -1)

Part 2:实例

  • 创建测试.txt文件,写入测试1,测试2,测试3
Sub test()
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    strNewFile = ThisWorkbook.Path & "\" & "测试.txt"

    Set objNewFile = objFSO.CreateTextFile(strNewFile, True)
    objNewFile.writeline ("测试1")
    objNewFile.writeline ("测试2")
    objNewFile.Close
'    objFSO.GetFile(strNewFile).Delete
'    Kill strNewFile

'    Const ForReading = 1, ForWriting = 2, ForAppending = 8, TristateTrue = -1
'其中TristateTrue 以什么方式打开文件,ASCII(0)或者Unicode(-1)
    Set strNewFileOpen = objFSO.OpenTextFile(strNewFile, 8, -1)
    strNewFileOpen.writeline ("测试3")

End Sub


程序运行结果截图




以上,为本次的介绍内容,下回见。

本文首发于微信公众号:Excel高效办公之VBA。排版和细节略作修改,发于头条

点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4