VBA excel多行字符串搜索



我想使用VBA excel宏在文本文件中搜索多行字符串。我尝试使用InStr函数。但它不像我预期的那样起作用。我的确切目标是读取存储在单元格中的多行字符串,并检查它是否在文本文件中可用。为此,我所做的是将文本文件读取到一个变量中,将保存在单元格中的字符串读取到另一个变量中,并使用使用二进制比较的Instr进行比较。InStr是否适用于多行字符串?如果没有,还有其他的比较方法吗?

这是我的代码

Public Function string_compare() As String
    Dim strFilename As String
    Dim strSearch As String
    strFilename = "D:test.txt"
    Dim strFileContent As String
    Dim iFile As Integer: iFile = FreeFile
    Open strFilename For Input As #iFile
    strFileContent = Input(LOF(iFile), iFile)
    Close #iFile
    strSearch = Sheet1.Cells(9, 1).Value
    If InStr(1, strFileContent, strSearch, vbBinaryCompare) > 0 Then
        MsgBox "success"
    Else
        MsgBox "failed"
    End If
End Function

当我检查两个字符串似乎是相同的。即使字符串相同,搜索结果也总是失败。任何建议都会有帮助的。

按照Tim和Mrig的建议,我从文本中删除了cr和crlf,如下所示。现在工作得很好。我可以用它来比较多行字符串。我在这里张贴我的代码段。希望它也能帮助到其他人。

Public Function stringcompare(sourcefile As String, Workbookname As Worksheet) As String
Dim strSearch As String
Dim strFileContent As String
Dim iFile As Integer: iFile = FreeFile
Open sourcefile For Input As #iFile
strFileContent = Input(LOF(iFile), iFile)
Close #iFile
strSearch = Workbookname.Cells(1, 1).Value
strFileContent = Application.WorksheetFunction.Substitute(strFileContent, vbCrLf, "")
strSearch = Application.WorksheetFunction.Substitute(strSearch, vbLf, "")
    If StrComp(strFileContent, strSearch, vbBinaryCompare) = 0 Then
        MsgBox "success"
    Else
        MsgBox "failed"
    End If
End Function

最新更新