【问题标题】:look up in a collection在集合中查找
【发布时间】:2020-05-04 12:03:47
【问题描述】:

我有这段代码(来自这里:https://stackoverflow.com/a/61501053/11458676)来加载一个 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

并且想要查找特定元素。是否有任何直接的方法可以在内容中搜索给定字符串的行号?

谢谢。

【问题讨论】:

  • 哪个'这个代码'?您是如何“在内存中加载 csv 文件”的?
  • @FaneDuru 修改

标签: excel vba collections


【解决方案1】:

请试试这段代码:

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")

它将返回已找到字符串的集合元素编号(在您的情况下为行号)...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    • 2016-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多