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.
vbLf(ASCII 10) as a line separator. A text file (on Windows) will typically bevbCrLf(ASCII 13 + ASCII 10). These will not match if you use Instr(), so you could try replacing thevbLfin the text from the cell withvbCrLfbefore using Instr()InStrfunction, write:strFileContent = Application.WorksheetFunction.Substitute(strFileContent, vbCrLf, "")andstrSearch = Application.WorksheetFunction.Substitute(strSearch, vbLf, "")Replace()function since Excel 2000. If the line-breaks are significant then you should normalize them to the same version: if they're not significant then you can just remove them altogether.