How to execute Open and Close function on multiple text files? [closed]

佐手、 提交于 2019-12-13 04:39:56

问题


I am trying below code but for some reason, it is not workning as the logic suggest.

myTxt = Application.GetOpenFilename("Text Files,*.txt", , , , True)

On Error Resume Next
filecount = UBound(myTxt)
On Error GoTo 0

If filecount = 0 Then MsgBox "No text file selected. Exiting now.", _
    vbExclamation: Exit Sub

For i = LBound(myTxt) To filecount
    fnum = FreeFile()
    Debug.Print fnum
    Open myTxt(i) For Input As #fnum
    lines = Split(Input$(LOF(fnum), #fnum), vbNewLine)
    Close #fnum

    '~~> Do stuffs here for text parsing...
Next

Basically, I want to work on multiple .txt files, open and load it to array.
Then close, do stuffs on the array and repeat the step for the succeeding files.
But it only gives me the parsing result for the 1st file.
Did I miss something in my code? What is the proper way to do this?


回答1:


Try this version (TRIED AND TESTED).

Option Explicit

Sub Sample()
    Dim MyData As String, strData() As String
    Dim i As Long, filecount As Long
    Dim myTxt

    myTxt = Application.GetOpenFilename("Text Files,*.txt", , , , True)

    On Error Resume Next
    filecount = UBound(myTxt)
    On Error GoTo 0

    If filecount = 0 Then MsgBox "No text file selected. Exiting now.", _
    vbExclamation: Exit Sub

    For i = LBound(myTxt) To filecount
        'Debug.Print myTxt(i)
        Open myTxt(i) For Binary As #1
        MyData = Space$(LOF(1))
        Get #1, , MyData
        Close #1
        strData() = Split(MyData, vbCrLf)

        'Debug.Print UBound(strData)
        '~~> Do stuffs here with strData for text parsing...
    Next
End Sub



回答2:


Posted as answer to avoid confusion: What makes the code elude parsing all the text files:

For j = LBound(lines) To UBound(lines)
    If mydate = 0 Then If IsDate(Trim(lines(j))) Then mydate = CDate(Trim(lines(j)))
    If UpdatePage(lines(j)) Then page = page + 1

        Select Case True
        Case page = 1
        Case page = 2
        .
        .
        Case page = 4
        End Select
    End If
Next
'page = 0
'mydate = 0

The commented line is what I missed in my original code.
So the Select Case routine is ignored since page did not reset.
So there's really no problem on the code itself.
Current code and what Siddharth Rout posted is working.



来源:https://stackoverflow.com/questions/23354764/how-to-execute-open-and-close-function-on-multiple-text-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!