单向可控硅电路图:vba 读写文本文件
来源:百度文库 编辑:偶看新闻 时间:2024/07/05 17:05:13
顺序文件的读用input/line input,写用write/print
2.打开二进制文件:open filename for binary as..
二进制文件的读用get,写用put
Write和Print以及Input是不能指定地址的,完全依赖文件指针。而Get和Put是对地址操作的。还有一个区别在于:顺序文件被打开后不能同时对一个文件号进行读写操作,假如你想对这个文件同时读写,需要用两个文件号打开。而二进制文件却可以同时进行读写操作。
由于Get和Put是对地址操作的,假如你想保存一个Integer类型的变量,那么下面的语句就会出毛病的:
Put #1,1,intValue1
Put #1,2,intValue2
由于Integer是占用两个字节的,你这样写会导致intValue1丢失高位字节。所以应该自行写一个函数计算地址。简单的地址计算函数是这样的:
Function AddressGetByRecNum(pRecNum As Long,pRecMiareg As Long,pRecLen As Integer) As Long
Dim tOutLng As Long
tOutLng=pRecNum*pRecLen+pRecMiareg
AddressGetByRecNum=tOutLng
End Function
pRecNum是变量的记录号码。
pRecMiareg是偏移量,假如你没有设计文件头,通常取1。
pRecLen是记录的字节长度,可以用常用。如果自动测试,一定要用LenB函数来取。
Sample:
Dim txt As String
txt = "d:\send.txt"
Dim strData As String
Open txt For Input As #2 '...读文件
Do While Not EOF(2)
Line Input #2, strData
Text1.Text = strData
Loop
Close #2
Open txt For Output as #1 '...写文件
strData="welcome"
Print #1, strData
加入回车加换行:Chr$(13) + Chr$(10)/vbCrLf,可换行
Open txt For Append As #1 文件后面追加,不会覆盖
Open txt For Binary as #3
Put #3,4,"aaa" '...写入数据
'...读取数据
Dim txt As String
txt = "d:\send.txt"
Dim TempFile As Long
Dim LoadBytes() As Byte
TempFile = FreeFile
Open txt For Binary As #TempFile
ReDim LoadBytes(1 To LOF(TempFile)) As Byte
Get #TempFile, , LoadBytes'...读取数据到数组
Close TempFile
Text1.Text = StrConv(LoadBytes, vbUnicode)
引文来源 vba 读写文本文件 — Windows Live