分享

VB文件追加和覆盖

 Ark.xu 2011-06-17
Private Sub ReadTxt(ByVal PathName As String)

Dim IntPrompt As Integer
Dim IntFileNo As Integer
Dim StrTxt As String

On Error GoTo ErrOccured
'Input和Output用于文本文件,而Binary和Random用于二进制文件(如:doc就是二进制文件)
IntFileNo = FreeFile() '文件句柄
'Open PathName For Input As IntFileNo '较简单的写法
Open PathName For Input Access Read Lock Read As IntFileNo
IntPrompt = MsgBox("只读一行还是全文读取?" & Chr(13) & Chr(10) & "点击“是”只读一行,点击“否”全文读取", vbInformation + vbYesNoCancel, "读取")
If IntPrompt = vbYes Then
'先清空文本
Txt.Text = ""
' 'Input语句在遇到第一个逗号或者空格则停止。通常用 Input # 从文件读出 Write # 写入的数据。
' Input #IntFileNo, StrTxt
'Line Input语句在遇到第一个回车(Chr(13))或回车换行(Chr(13)+Chr(10))时停止
Line Input #IntFileNo, StrTxt
Txt.Text = StrTxt
ElseIf IntPrompt = vbNo Then
'先清空文本
Txt.Text = ""
Do While Not EOF(IntFileNo)
Line Input #IntFileNo, StrTxt
Txt.Text = Txt.Text & StrTxt & Chr(13) & Chr(10)
Loop
Else
MsgBox "读取动作被取消", vbInformation + vbMsgBoxRtlReading, "Cancel"
Exit Sub
End If
'这里的判断其实是多余的,如果IntFileNo作为窗体级的变量则可以加此判断
If IntFileNo <> 0 Then
Close IntFileNo
End If
Exit Sub
ErrOccured:
'带有搞笑性质的MsgBox
IntPrompt = MsgBox("分特!没读成功啊!重读吗?", vbMsgBoxRtlReading + vbCritical + vbYesNo, "真笨")
If IntPrompt = vbYes Then Resume
End Sub

Private Sub WriteTxt(ByVal PathName As String)

Dim IntPrompt As Integer
Dim StrTxt As String
Dim myVariant As Variant

'On Error GoTo ErrOccured
StrTxt = Txt.Text
IntPrompt = MsgBox("覆盖文件还是追加?" & Chr(13) & Chr(10) & "点击“是”覆盖,点击“否”追加", vbYesNoCancel + vbQuestion, "写入")
Select Case IntPrompt
Case vbYes
'覆盖
Open PathName For Output Lock Write As #1
'Print和Write的区别在于:如果今后想用 Input # 语句读出文件的数据,就要用 Write # 语句而不用 Print # 语句将数据写入文件
'通常用 Print # 将 Line Input # 语句读出的数据从文件中写出来。
Print #1, StrTxt
'与 Print # 语句不同,当要将数据写入文件时,Write # 语句会在项目和用来标记字符串的引号之间插入逗号。没有必要在列表中键入明确的分界符。
'通常用 Write # 将 Input # 语句读出的数据写入文件。
' Write #1, StrTxt
Close #1
Case vbNo
'追加
Open PathName For Append Lock Write As #1
Print #1, StrTxt
' Write #1, StrTxt
Close #1
Case Else
MsgBox "写入动作被取消", vbInformation + vbMsgBoxRtlReading, "Abort"
Exit Sub
End Select
MsgBox "写入成功!"
'打开文件观察结果(暂时未写)

Exit Sub
ErrOccured:
IntPrompt = MsgBox("分特!没写成功啊!重写吗?", vbMsgBoxRtlReading + vbExclamation + vbYesNo, "真笨")
If IntPrompt = vbYes Then Resume
End Sub

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多