- 工程|部件—>Microsoft DataGrid Control 6.0(SP6);工程|引用—>Microsoft Scripting Runtime;工程|部件—>Microsoft ADO Data Control 6.0
- 窗体上放置两个按钮 一个dataGrid 一个ADODC
- 程序代码
Option Explicit
Dim rs As Recordset
Const ReadMode As String = 1
Const WriteMode As String = 2
Dim i As Integer
Private Sub Command1_Click()
Dim output As String
Dim ans As String
ans = MsgBox("确定保存?", vbOKCancel)
If ans = vbOK Then
rs.MoveFirst
'将记录转换成字符串
output = rs.GetString(adClipString, rs.RecordCount, vbTab, vbCrLf, "null") '文件输出数据
OpenFile(WriteMode).Write (output) '将字符串写入文件
Else
Exit Sub
End If
End Sub
Private Sub Command2_Click()
Unload Me
End Sub
Private Sub Form_Load()
If FoundRs(OpenFile(ReadMode)) Then
Set DataGrid1.DataSource = rs
Else
MsgBox "打开不成功!"
End If
End Sub
Private Function FoundRs(ts As TextStream) As Boolean '创建记录集,并将txt文件中的数据显示
Dim s
On Error GoTo perrors
Set rs = New Recordset
'以下为创建标题栏字段
With rs
.Fields.Append "stuid", adBSTR
.Fields.Append "wordid", adBSTR
.Fields.Append "excelid", adBSTR
.Fields.Append "wordsubmit", adBSTR
.Fields.Append "excelsubmit", adBSTR
.Open
End With
'将文本文件数据读入到rs中
Do While ts.AtEndOfStream <> True
s = Split(ts.ReadLine, vbTab) 'txt文件通过tab键分割
With rs
.AddNew '增加新的一行
'逐行读取txt文件
For i = 0 To 4
.Fields(i) = s(i)
Next
.Update
End With
Loop
'成功返回true
FoundRs = True
Exit Function
perrors:
FoundRs = False
End Function
Private Function OpenFile(x As String) As TextStream
Dim fso As New FileSystemObject
Dim fil As File
Dim ts As TextStream
Dim s As String
Dim strPath As String
strPath = "D:" & "/paperuser.txt" '设置文件路径
'以下为打开文件
Set fil = fso.GetFile(strPath) '获取txt文件的指针
Set ts = fil.OpenAsTextStream(x) '以文本流的方式读取数据放入ts中
Set OpenFile = ts
End Function