从Excel中记录并使用vba在.csv / .txt文件中搜索多个记录

时间:2016-05-22 13:04:53

标签: vba excel-vba csv excel

我正在循环Excel(例如,记录城市="巴黎")然后想要从.csv文件中检索多个记录(可能有可能检索.csv文件中有关的多个记录城市巴黎)

这是.txt的基本结构,它是制表符分隔文件。

1 Tokyo JA  test    Tokyo   "test, testttttttttt."  "images url to download delimited by ,"
2 Tokyo JA  test    Tokyo   "test, testttttttttt."  "images url to download delimited by ,"
3 Paris FR  test    Tokyo   "test, testttttttttt."  "images url to download delimited by ,"

任何人都可以帮我这个,请注意上面的文件是.txt文件,并说我想知道.txt / csv文件中每条Excel记录有多少记录(计数),所以我想要做我系统中需要的其他活动。

这是我的代码:

currPath1 = "C:\sourceexcel.xlsx"
    currentPath2 = "C:\CSVtoberead.txt"
fileNum =FreeFile()
    Open currentPath2 For Input As fileNum
    totoalRows= xlsheet.UsedRange.Rows.Count
        startrow1 =1
        PreviousCity=""
        For x= startRow To totoalRows
            currentCity = xlsheet.Cells(startRow,3 ).value  '' this is city from excel sheet
            Do While Not EOF( fileNum )
                Line Input #fileNum, txt  '''file to read .txt file
                parseRecord = Split (txt,Chr(9))
                If  parserecord(1)= currentCity Then  

1 个答案:

答案 0 :(得分:0)

对工作表中每个城市的一次重复读取文本文件是非常低效的。相反,您可以只读取一次文件,将每行中的数据加载到由城市键入的字典中,其值是数组的集合(每个数组对应于一行的分割)。像这样:

Function ExtractData(fname As String, colNumber As Long, Optional delim As String = vbTab) As Variant
    'Takes a delimited txt file and returns a dictionary
    'keyed by the entries in the specified column
    'the values for a key is a collection of split lines

    Dim fileNum As Long
    Dim txt As String
    Dim C As Collection
    Dim d As Variant, k As Variant, parseRecord As Variant

    Set d = CreateObject("Scripting.Dictionary")

    fileNum = FreeFile()
    Open fname For Input As fileNum

    Do While Not EOF(fileNum)
        Line Input #fileNum, txt  '''file to read .txt file
        parseRecord = Split(txt, delim)
        k = parseRecord(colNumber)
        If d.exists(k) Then
            d(k).Add parseRecord
        Else
            Set C = New Collection
            C.Add parseRecord
            d.Add k, C
        End If
    Loop

    Close #fileNum

    Set ExtractData = d

End Function

您应该能够使用上述功能来简化您的代码。为了让您了解它是如何工作的,我将您的数据(将选项卡替换为空格)复制到文本文件中并运行:

Sub test()
    Dim v As Variant
    Set v = ExtractData("C:/Programs/test.txt", 1)
    Debug.Print v("Tokyo").Count
    Debug.Print v("Paris").Count
    Debug.Print Join(v("Tokyo")(2), "/")
End Sub

输出结果为:

2 
1 
2/Tokyo/JA/test/Tokyo/"test, testttttttttt."/"images url to download delimited by ,"

扩展一下:在代码的开头只运行一次函数,并将其分配给变量(例如v)。然后遍历包含城市的电子表格列。对于每个城市,v.Exists(city)可以检查城市是否出现在数据中。如果是,则v(city).Count会告诉您多少次,v(city)(i)之类的内容可用于访问与该城市对应的各行数据。如果j是特定列号,则v(city)(i)(j)将给出(作为字符串)给定城市的出现i的列j中的数据。