如何计算在文件中找到的字符串的实例

时间:2019-01-28 18:48:49

标签: excel vba

我正在使用此代码在文件夹中的所有相关文件中进行搜索。

如何添加在每个文件中找到字符串的次数,以便可以返回该数字?如果很重要,我确实知道我要搜索的字符串只会在每一行文本中找到一次。

我尝试了一堆随机的东西,但是我只得到“ 1”,这是错误的。

Sub StringExistsInFile()

    Dim theString As Variant
    Dim path As String
    Dim StrFile As String
    Dim fso As New FileSystemObject
    Dim file As TextStream
    Dim line As String

    theString = Userform1.TextBox1.Text
    path = "P:\prg\"
    StrFile = Dir(path & "*.dp")


    Do While StrFile <> ""

        Set file = fso.OpenTextFile(path & StrFile)

        Do While Not file.AtEndOfLine

            line = file.ReadLine
            If InStr(1, line, theString, vbTextCompare) > 0 Then
                Userform1.ListBox1.AddItem (StrFile)
                Exit Do
            End If

        Loop

        file.Close

        Set file = Nothing
        Set fso = Nothing

        StrFile = Dir()

    Loop

End Sub

1 个答案:

答案 0 :(得分:0)

当您循环执行AtEndOfLine时,您的代码在每个文件的第一个空行处停止。 请尝试以下方法:

Sub StringExistsInFile()
    Dim theString As Variant
    Dim path As String
    Dim StrFile As String
    Dim fso As New FileSystemObject
    Dim file As TextStream
    Dim line As String        
    Dim amount As Long
    Dim theResult as String

    theString = Userform1.TextBox1.Text
    path = "P:\prg\"
    StrFile = Dir(path & "*.dp")

    Do While StrFile <> ""
        Set file = fso.OpenTextFile(path & StrFile)
        amount = 0
        Do While Not file.AtEndOfStream
            line = file.ReadLine
            If InStr(1, line, theString, vbTextCompare) > 0 Then
                amount = amount + 1
            End If
        Loop
        If amount > 0 Then
            Userform1.ListBox1.AddItem (StrFile & ": " & theString & " = " & amount)
        End If
        file.Close
        Set file = Nothing
        Set fso = Nothing
        StrFile = Dir()
    Loop
End Sub