Reading in data from text file into a VBA array

后端 未结 2 859
野性不改
野性不改 2021-01-06 10:45

I have the following VBA code:

Sub read_in_data_from_txt_file()

Dim dataArray() As String
Dim i As Integer

Const strFileName As String = \"Z:\\sample_text.         


        
相关标签:
2条回答
  • 2021-01-06 10:50

    Here is a clean code on how to use for each loop in VBA

    Function TxtParse(ByVal FileName As String) As String
        Dim fs, ts As Object
        Dim strdic() As String
        Dim oitem As Variant
        Set fs = CreateObject("Scripting.FileSystemObject")
        Set ts = fs.OpenTextFile(FileName, 1, False, -2)
    
        strdic = Split(ts.ReadAll, vbLf)
    
        For Each oitem In strdic
            If InStr(oitem, "YourString") <> 0 Then
            Else
                If InStr(1, oitem, vbTab) <> 0 Then
                        Debug.Print "Line number is : "; "'" & Replace(oitem, vbTab, "','") & "'"
                Else
                        Debug.Print "Line number is : "; "'" & Replace(oitem, ",", "','") & "'"
                End If
            End If
        Next
    End Function
    
    
    0 讨论(0)
  • 2021-01-06 11:01

    What you have is fine; if everything ends up in dataArray(0) then the lines in the file are not using a CrLf delimiter so line input is grabbing everything.

    Instead;

    open strFileName for Input as #1
    dataArray = split(input$(LOF(1), #1), vbLf)
    close #1
    

    Assuming the delimiter is VbLf (what it would be coming from a *nix system)

    0 讨论(0)
提交回复
热议问题