一个从数据库导出的文本文件部分数据如下: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

解决方案 »

  1.   

    Dim j As Integer:
    这句没用到,是我程序拷出来时忘了删
      

  2.   

    既然是导入数据库..
    直接用RS打开吧..
    参考一下:Dim conn As New ADODB.Connection
    Dim rs As New ADODB.RecordsetPrivate 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 SubPrivate 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
      

  3.   

    可能里面不是空格吧,有可能是tab键,你这样试试
    x = Replace(x, vbtab, "  ")
    x = Replace(x, "  ", " ")
      

  4.   


    a = Split(x, " ")   '将数据分割到数组A中
    换成
    a = Split(x,vbTab)   '将数据分割到数组A中
    试试
      

  5.   

    http://expert.csdn.net/Expert/topic/2948/2948405.xml?temp=.3163111