DataGrid读写txt文件

  1. 工程|部件—>Microsoft DataGrid Control 6.0(SP6);工程|引用—>Microsoft Scripting Runtime;工程|部件—>Microsoft ADO Data Control 6.0
  2. 窗体上放置两个按钮 一个dataGrid 一个ADODC
  3. 程序代码

        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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhchyun2008

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值