VBA-文件的基本操作(及将文件操作封装成类)

1.首先我们来学习一下基本的文件操作

(1)写入代码

 Sub print写入()
    'Open ThisWorkbook.Path & "\text.txt" For   Append As #1'追加写入
     Open ThisWorkbook.path & "\text.txt" For Output As #1 '写入的文件每次会被覆盖
     Print #1, "谭可", "234454" '会自动添加空格
     Print #1, "谭可"; "234454" '紧接前面的数据写入
     Print #1, '写入空行
   
     Close #1
    
      MsgBox "写入成功"
 End Sub

扫描二维码关注公众号,回复: 2300265 查看本文章

或者用write写入,这两种方式有点区别,具体差别在哪里,可以自己运行试试看

Sub write写入()
   Open ThisWorkbook.path & "\text.txt" For Output As #1
     Write #1, "谭可", "234454" '会自动添加双引号和逗号
     Close #1
     MsgBox "写入成功"
End Sub

(2)读取数据(这里提供两种方法,都可以读取文件)

Sub lineinput读取()
 Dim filename As String
 filename = ThisWorkbook.path & "\sdd.txt"
 Open filename For Input As #1
 Dim str As String, s As String
 Do While Not EOF(1) 'EOF(文件号),判断是否达到文件末尾
 Line Input #1, str
  s = s & str
 Loop
 Close #1
 MsgBox s
End Sub
Sub input读取()
 Dim filename As String
 filename = ThisWorkbook.path & "\sdd.txt"
  Open filename For Input As #1
  Dim s As String
  Do While Not EOF(1)
    s = s & Input(1, 1) 'input(读取字符数,文件号)
    Loop
    Close #1
    MsgBox s
 
End Sub

2.类的封装(将文件操作写成类,可以直接调用里面的方法,提高编程效率)

Option Explicit
'写入 optional 表示可选参数,意思就是调用的时候,该参数可以传入,也可以不传入
Sub writealltext(filename As String, str As String, Optional appendornot As Boolean = False)
    Dim number As Integer
    number = FreeFile
    If appendornot Then
     Open filename For Append As #number '追加方式打开文件
    Else
        Open filename For Output As #number '覆盖方式打开文件
    End If
    Print #number, str;
    Close #number '关闭
End Sub
'读取所有行,返回字符串数组
 Function readalllines(filename As String) As String()
 
  Dim arr() As String, k As Integer, number As Integer
  number = FreeFile
  Open filename For Input As #number '打开文件
  Do While Not EOF(number)
  '建议把数据做成“步进式扩容”
    k = k + 1
    ReDim Preserve arr(1 To k) As String
    Line Input #number, arr(k)
   Loop
Close #number
readalllines = arr

 End Function
Function readalltext(filename As String) As String
    Dim number As Integer, s As String
    number = FreeFile '产生一个当前可用的最小文件号
    Open filename For Input As #number  '打开文件
    Do While Not EOF(number)     '循环读取
        s = s & Input(1, number)
    Loop
    Close #number '关闭
    readalltext = s
   
End Function

3.调用的方法也很简单

Option Explicit
Sub 测试()
Dim file As New clsfile
Dim path As String
path = ThisWorkbook.path & "\text.txt"
MsgBox file.readalltext(path)
Dim arr() As String
arr = file.readalllines(path)
file.writealltext path, "我爱你"

End Sub

4.可以将文件操作的方法进行完善,后面可以直接使用

猜你喜欢

转载自blog.csdn.net/qq_41777527/article/details/81045684