EXCEL VBA 创建并写入TXT文件

创建写入TXT_20191201001734.png

自定义创建并写入TXT,需要处理文件夹和文件名的是否存在及正确的问题!

'-----------------------------------------------
'创建并写入TXT文件
'-----------------------------------------------
Function openTXT(ByVal Content As String, Optional ByVal FileName As String = "", Optional ByVal FilePath As String = "") As Boolean

    Dim FullName As String  '完整文件名
    
    '处理文件夹
    If FilePath = "" Then
        FilePath = ThisWorkbook.path    '为空时默认当期文件夹
    Else
        If Right(FilePath, 1) <> "\" Then FilePath = FilePath & "\"     '填补右侧斜杠
        If PathExists(FilePath) = False Then
            FilePath = ThisWorkbook.path
            MsgBox "您输入的文件夹地址有误,新地址为文件所在地址"
        End If
    End If
    
    '处理文件名
    If FileName = "" Then
        FileName = "YEYU_" & Format(Now(), "yyyymmddhhmmss")
    End If
    
    '拼接完整地址
    FullName = FilePath & "\" & FileName & ".txt"
    
    '创建并写入文件
    Open FullName For Output As #1
    Print #1, Content
    Close #1
    
    '输出结果(判断是否创建成功)
    openTXT = FileExists(FullName)
    
End Function

'+------------------------------------------------------------
'| 判断路径Path是否存在
'+------------------------------------------------------------
Public Function PathExists(pname) As Boolean
    Dim x As String
    On Error Resume Next
    x = GetAttr(pname) And 0
    If Err = 0 Then PathExists = True _
      Else PathExists = False
End Function
 
'+------------------------------------------------------------
'| 判断文件File是否存在
'+------------------------------------------------------------
Private Function FileExists(fname) As Boolean
    Dim x As String
    x = Dir(fname)
    If x <> "" Then FileExists = True _
        Else FileExists = False
End Function
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、基础知识:1、JVM、JRE和JDK的区别:JVM(Java Virtual Machine):java虚拟机...
    杀小贼阅读 2,427评论 0 4
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,159评论 1 32
  • 个人学习批处理的初衷来源于实际工作;在某个迭代版本有个BS(安卓手游模拟器)大需求,从而在测试过程中就重复涉及到...
    Luckykailiu阅读 4,799评论 0 11
  • 写在前面的话 代码中的# > 表示的是输出结果 输入 使用input()函数 用法 注意input函数输出的均是字...
    FlyingLittlePG阅读 2,977评论 0 9
  • 一、Python简介和环境搭建以及pip的安装 4课时实验课主要内容 【Python简介】: Python 是一个...
    _小老虎_阅读 5,848评论 0 10