RT,比如一个目录下有10个CSV文件,如何按顺序读取他们?同时获取他们各自的文件名呢?

解决方案 »

  1.   

    '添加.驱动器列表(DriveListBox),目录列表(DirListBox),文件列表(FileBox)和text1各一个
    Dim ex As Object
    Dim wb As Object
    Dim sh As Object
    Dim strFileA As String
    Private Sub Command1_Click()
    Dim i As Integer
    Set ex = CreateObject("Excel.Application") For i = 0 To File1.ListCount - 1
      Set wb = ex.Workbooks.Open(File1.Path & "\" & File1.List(i))  '打开你文件里所有文件
      Set sh = wb.Sheets(1) '打开工作表1
       'Text2.Text = Text1.Text & File1.List(i) & vbCrLf  '这行可以得到文件名.不过没必要,因为Filebox里已经有了
        strFileA = sh.cells(1, 1)  '提取所有文件的第一行第一列数据
        Text1.Text = Text1.Text & strFileA & vbCrLf  ' 结果
      ex.Quit
      Next i
      Set ex = Nothing
      Set wb = Nothing
      Set sh = Nothing
    End Sub
    Private Sub Dir1_Change()
    File1.Path = Dir1.Path
    End Sub
    Private Sub Drive1_Change()
    Dir1.Path = Drive1.Drive
    End Sub
    Private Sub Form_Load()
    File1.Pattern = "*.CSV" '设置你的文件类型
    End Sub
      

  2.   


    不知道你的“依次”是依的什么顺序。如果不需要特别排序的话,用 Dir 就可以。Dim strPath As String, strFileName As String, strLine As StringstrPath = "D:\test"
    strFileName = Dir(strPath & "\*.csv")Text1 = ""
    Do While strFileName > ""
        Text1 = Text1 & IIF(Text1 > "", vbCrLf, "") & strFileName & vbCrlf
        Open strPath & "\" & strFileName For Input As #1
        Do Until EOF(1)
            Line Input #1, strLine
            strLine = Replace(strLine, ",", vbTab)
            Text1 = Text1 & strLine & vbCrLf
        Loop
        Close #1
        Text1 = Text1 & vbCrLf
        strFileName = Dir
    Loop