这样一行一行读取文本文件(txt文件)为何取值不对?急!

cgj36254605 2004-04-10 11:15:23
一个从数据库导出的文本文件部分数据如下:

num branch vest_in_site
8300207 8295 121
8300241 8295 121
8300242 8295 121
8300245 8295 121
8300247 8295 121

----------------------------------------------------
写如下函数一行一行读取:
Public Function ImportSpeData() As Boolean
Dim a$(), i%, x$, n%, pos%

Dim phsnum As String
Dim bureau As String
Dim channel As String


On Error GoTo errhandle
CommonDialog1.Filter = "txt File|*.txt"
CommonDialog1.ShowOpen
Dim FileName As String

FileName = CommonDialog1.FileName
Text1.Text = FileName
Open FileName For Input As #1 ' 打开文件
Do While Not EOF(1)
Line Input #1, x
'以下循环是将数据间的多个空格压缩成一个空格,因为可能字段值间空格会变
Do
n = Len(x)
x = Replace(x, " ", " ")
Loop While n > Len(x)

If x Like "*[A-Za-z]*" Then '如果含有字母,表示为第一行,是字段名,不处理
Else
a = Split(x, " ") '将数据分割到数组A中
Dim j As Integer
phsnum = a(0) '为什么在这里a(0)的值为一整行的数据,而下面a(1)没值,于是越界退出?
bureau = a(1)
channel = a(2)
End If
Loop
ImportSpeData = True
Close #1
Exit Function
errhandle:
ImportSpeData = False
End Function
...全文
258 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
wumylove1234 2004-04-11
  • 打赏
  • 举报
回复
直接用ADO操作.
northwolves 2004-04-11
  • 打赏
  • 举报
回复
http://expert.csdn.net/Expert/topic/2948/2948405.xml?temp=.3163111
wumy_ld 2004-04-10
  • 打赏
  • 举报
回复

a = Split(x, " ") '将数据分割到数组A中
换成
a = Split(x,vbTab) '将数据分割到数组A中
试试
lxqlogo0 2004-04-10
  • 打赏
  • 举报
回复
可能里面不是空格吧,有可能是tab键,你这样试试
x = Replace(x, vbtab, " ")
x = Replace(x, " ", " ")
华芸智森 2004-04-10
  • 打赏
  • 举报
回复
既然是导入数据库..
直接用RS打开吧..
参考一下:

Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset

Private Sub Form_Load()
Dim ConnStr As String

ConnStr = "Provider=MSDASQL.1;" & _
"DRIVER={Microsoft Text Driver (*.txt; *.csv)};" & _
"DBQ=E:\DEMO\txt"
conn.Open ConnStr

rs.CursorLocation = adUseClient
rs.Open "Select * From score2.txt", conn, adOpenDynamic, adLockPessimistic

DisplayRecordset
End Sub

Private Sub DisplayRecordset() ' 列出 Recordset 的所有记录
Dim S As String, i As Integer

rs.MoveFirst
List1.Clear
While Not rs.EOF
S = ""
For i = 0 To rs.Fields.Count - 1
S = S & rs.Fields(i).Value & vbTab
Next
List1.AddItem S
rs.MoveNext
Wend
End Sub
cgj36254605 2004-04-10
  • 打赏
  • 举报
回复
Dim j As Integer:
这句没用到,是我程序拷出来时忘了删

7,763

社区成员

发帖
与我相关
我的任务
社区描述
VB 基础类
社区管理员
  • VB基础类社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧