искать в коллекции - PullRequest
       16

искать в коллекции

0 голосов
/ 04 мая 2020

У меня есть этот код (отсюда: { ссылка }) для загрузки файла CSV и выбора некоторых элементов.

    Option Explicit

Function txtfileinCol(filename As String) As Collection
' loads the content of a textfile line by line into a collection
    Dim fileContent As Collection
    Set fileContent = New Collection

    Dim fileNo As Long
    Dim txtLine As String

    fileNo = FreeFile
    Open filename For Input As #fileNo
    Do Until EOF(fileNo)
        Line Input #fileNo, txtLine
        fileContent.Add txtLine
    Loop

    Close #fileNo

    Set txtfileinCol = fileContent

End Function
Function getColRow(fileLines As Collection, rowNo As Long, colNo As Long, Optional delimiter As String) As String

    Dim vdat As Variant

    On Error GoTo EH:

    If Len(delimiter) = 0 Then
        delimiter = ";"
    End If

    vdat = fileLines.Item(rowNo)    'here you get the line
    vdat = Split(vdat, delimiter)   'now you split the line with the delimiter

    getColRow = vdat(colNo - 1)     'now you retrieve the content of the column
    Exit Function
EH:
    getColRow = ""

End Function

Sub Testit()

    Dim filename As String
    Dim col As Collection

    filename = "C:\Temp\FILE.csv"
    Set col = txtfileinCol(filename)   

    Debug.Print getColRow(col, 10, 2, ";") 

End Sub

и хотите найти указанный c элемент. Есть ли какой-нибудь правильный способ найти номер строки данной строки внутри содержимого?

Спасибо.

1 Ответ

0 голосов
/ 04 мая 2020

Попробуйте этот кусок кода, пожалуйста:

Private Function rowFromString(col As Collection, strSearch As String) As Long
   Dim i As Long
   For i = 1 To col.count
        If InStr(col(i), strSearch) > 0 Then
            rowFromString = i: Exit Function
        End If
   Next i
End Function

Вы можете назвать его как:

Debug.Print rowFromString(col, "your search string")

Он вернет номер элемента коллекции (в вашем случае, номер строки ) где строка была найдена ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...