在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
1. 打开文件(Open) Open 文件名 [For模式][Access 存取类型][锁定]As [#]文件号[Len=记录长度] 说明: (1)文件名; (2) 模式用于指定文件访问的方式,包括: (3)文件号(或称文件缓冲区) (4)存取类型:访问文件的类型,为Read(只读)、Write(只写)、Read Write(读写) (5)锁定:限制其他用户或其他进程对文件进行读写操作 Shared(共享)、LockRead(禁止读)、Lock Write(禁止写)、 Lock Read Write(禁止读写) (6)Len:用来指定每个记录的长度(字节数) 示例: Open"d:\cj1.dat" For Output As #1 2. 关闭文件(Close) 打开的文件使用完后必须关闭。 关闭文件的语句格式: 示例: Close#1 1. Write语句 在最后一个字符写入后,插入一个回车换行符(Chr(13) + Chr(10)),以此作为记录结束的标记。 示例:Write#1, "Good Afternoon", 1998
Private Sub CommandButton1_Click() Dim num As String * 6, name As String * 8, score As Integer num = TextBox1.Text name = TextBox2.Text score = Val(TextBox3.Text) Write #1, num, name, score TextBox1.Text = "" TextBox2.Text = "" TextBox3.Text = "" TextBox1.SetFocus End Sub Private Sub CommandButton2_Click() Close #1 End End Sub Private Sub UserForm_Initialize() Open ThisWorkbook.Path & "\1.txt" For Output As #1 End Sub 运行结果~
读取数据,用For...Next 语句
Sub 的开发商的() Dim n As String, m As String, s As Integer Open ThisWorkbook.Path & "\1.txt" For Input As #1 For i = 1 To 5 Input #1, n, m, s Cells(i, 1) = n Cells(i, 2) = m Cells(i, 3) = s Next Close #1 End Sub
2. Print语句 格式:Print #文件号[,表达式表] 示例: 先用Input方式打开文件,然后采用Input或LineInput语句从文件中读出数据。通常,Input用来读出Write写入的记录内容,而Line Input用来读出Print写入的记录内容 1.Input语句 距离:
Sub sj() Open ThisWorkbook.Path & "\data1.txt" For Output As #1 a = 123: b$ = "ABCD" '在同一行赋值,用“:” Write #1, a, b$ Close #1 Open ThisWorkbook.Path & "\data1.txt" For Input As #1 Input #1, c, d$ Close #1 Debug.Print c, d$ End Sub
Sub dfjslkdf() Open ThisWorkbook.Path & "\num2.txt" For Append As #1 For i = 51 To 200 If i Mod 7 = 0 Then Write #1, i Next Close #1 End Sub Sub dfhdfdffdfdfdk() k = 0 Open ThisWorkbook.Path & "\num2.txt" For Input As #1 Do While Not EOF(1) Input #1, x Debug.Print x, k = k + 1 If k Mod 4 = 0 Then Debug.Print Loop End Sub
Debug.Print i, 在一行输出,中间空很多的空格,具有一定的格式 Debug.Print i; 在一行输出,中间空很少的空格,具有一定的格式 可以加入If i Mod 2 = 0 Then Debug.Print 可以进行换行 Print也有相似的用法: 从TXT中读取数据,数据中间可以是空格、半角逗号
Sub dhfkd() k = 0 Dim arr(1 To 1100) As Variant Open ThisWorkbook.Path & "\num2.txt" For Input As #1 Do While Not EOF(1) 'EOF(1)用来判断#1是否读到头了,到头返回TRUE Input #1, x '读取一个数据 k = k + 1 arr(k) = x '将读取的数据存在一个数组中 Loop k = 0 For i = 1 To 10 For j = 1 To 110 k = k + 1 Cells(j, i) = arr(k) Next Next Close #1 End Sub
2.Line Input语句 格式:LineInput #文件号,字符型变量 用Line input来读取由Print写入的数据,Line Input读取一整行的数据~
Sub djhfdljf() Open ThisWorkbook.Path & "\mytxt.txt" For Output As #1 a = 123: b$ = "SBCD" Print #1, a, b$ Print #1, a; b$ Close #1 Open ThisWorkbook.Path & "\mytxt.txt" For Input As #1 Line Input #1, x$ Debug.Print x$ Line Input #1, x$ Debug.Print x$ Close #1 End Sub
3.Input函数
格式:Input(字符数,#文件号) |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论