问题
I want to search a multi line string in a text file using VBA excel macro. I tried using InStr function.But its not working as I expected. My exact aim is to read a multi line string stored in a cell and check whether it is available in a text file. For that what i did is read the text file in to a variable, reading the string saved in the cell to another variable and comparing using Instr using binary comparison. Will InStr work for multi line string? If not any any other way to compare it?
This is my code
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
When I checked the strings both seems to be identical.Even though the strings are identical, the searching result always failing. Any suggestions will be helpful.
回答1:
As Tim and Mrig suggested I removed the cr and crlf from the text as follows. Now its working fine.I could use this for comparing multi line strings.I am posting my code segment here.Hope it may help somebody else too.
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
来源:https://stackoverflow.com/questions/38156999/vba-excel-multiline-string-search