2016-07-02 158 views
0

我想使用VBA excel宏在文本文件中搜索多行字符串。 我試過使用InStr函數,但它沒有按照我的預期工作。我的確切目標是讀取存儲在單元格中的多行字符串,並檢查它是否在文本文件中可用。爲此,我將文本文件讀入一個變量,將單元格中保存的字符串讀入另一個變量,並使用Instr使用二進制比較進行比較。 InStr是否適用於多行字符串?如果沒有任何其他方式來比較它?VBA excel多行字符串搜索

這是我的代碼

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 

當我檢查琴絃都似乎identical.Even雖然字符串相同,搜索結果總是失敗。任何建議都會有所幫助。

+0

你有沒有嘗試連接在一起的線? – KyloRen

+1

Excel單元格中的多行字符串通常將'vbLf'(ASCII 10)作爲行分隔符。一個文本文件(在Windows上)通常是'vbCrLf'(ASCII 13 + ASCII 10)。如果你使用Instr(),這些不匹配,所以你可以在使用Instr() –

+0

之前用'vbCrLf'替換單元格文本中的'vbLf'。正如@TimWilliams所建議的,在使用'InStr'函數之前,寫:strFileContent = Application.WorksheetFunction.Substitute(strFileContent,vbCrLf,「」)和'strSearch = Application.WorksheetFunction.Substitute(strSearch,vbLf,「」)' – Mrig

回答

0

正如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