首页 > 解决方案 > 如何将 .txt 文件中的单词与数组进行比较并将索引记录在另一个数组 VBA 中

问题描述

我有这个文本文件,当粘贴到 Excel 电子表格中时,它以制表符分隔,大约有 1,000 列和 12,000 行。我的目标是有某种方法可以比较字符串数组

arWords = Array("Title1", "Title2", "Title3")

到该 .txt 文件中的列标题。找到匹配项时,我想知道在哪个“列”中找到了该单词,并将其放入另一个数组中。在此示例中,它将是一个由 3 个整数组成的数组,每个整数表示找到每个 Title 的哪一列。我的目标是最终得到一个看起来像这样的数组。

listIndex = array(159, 393, 400)

如果我在 arWords 中包含 4 个标题,那么我最终会得到一个由 4 个整数组成的数组,代表它们的列 #。这是我的代码,它不是很好,我很不擅长这个,但仍然感谢!

Const ForReading = 1
Dim FSO, FileIn, strTmp

Set FSO = CreateObject("Scripting.FileSystemObject")
Set FileIn = FSO.OpenTextFile(movietitles.txt, ForReading)


arWords = Array("Title1", "Title2", "Title3")
size = UBound(arWords) - LBound(arWords) + 1
Dim listIndex() As Integer
ReDim listIndex(size)

Do Until FileIn.AtEndOfStream
    strTmp = FileIn.ReadLine
    If Len(strTmp) > 0 Then
        For i = 0 To UBound(arWords)
            If InStr(1, strTmp, arWords(i), vbTextCompare) > 0 Then
                listIndex(i) = i
                Exit For
            End If
        Next
    End If
Loop

FileIn.Close
     

    ReDim yArray(1 To lColumn)
    Dim Counter As Integer
       For Counter = 1 To lColumn
            yArray(Counter) = 9
        Next Counter
        
    For Each Index In listIndex
        yArray(Index) = 1
    Next Index

标签: arraysexcelvbaimport

解决方案


如果我在阅读您的评论后的假设是正确的,请尝试下一个代码。我假设标题位于文本文件的第一行。无需在 Excel 中打开它:

Sub MatchStringArrayToHeaders()
   Dim fileName As String, arWords, arrTxt, arrH, arrFin, El, mtch
   Dim k As Long, headRow As Long i As Long
   fileName = ThisWorkbook.path & "\MyTestFile.txt" 'use here your text file full name
   
   arWords = Array("Title1", "Title2", "Title3")
   ReDim arrFin(UBound(arWords)) 'redim the final array to be returned
   'put all the text file content in an array of rows:
   arrTxt = Split(CreateObject("Scripting.FileSystemObject").OpenTextFile(fileName, 1).ReadAll, vbCrLf)
   
   'find the header row: __________________________
   For i = 0 To UBound(arrTxt)
      arrH = Split(arrTxt(i), vbTab)
      If UBound(arrH) > 0 Then
        If arrH(1) <> "" Then HeaderRow = i: Exit For
      End If
   Next i
   '_______________________________________________
   arrH = Split(arrTxt(headRow), vbTab)
   
   For Each El In arWords
        mtch = Application.match(El, arrH, 0) 'return the matching header number
        If IsNumeric(mtch) Then               'if a match could be found
            arrFin(k) = mtch: k = k + 1       'put the column number in the final array
        Else
            'if not any match, write in Immediate Window the not matching string
            Debug.Print El & " could not be found in the headers row..."
        End If
   Next
   'Only to visually check the returned array:
   Debug.Print Join(arrFin, "|") 'the obtained array is joined using "|" separator and returned in Immediate Window (`Ctrl + G`, being in VBE).
End Sub

如果标题行并非始终相同,请给我此标题行的第 1 列标记,我将调整代码以首先搜索此标记,设置标题行并使用它...


推荐阅读