2016-07-02 2 views
0

VBA Excelマクロを使用してテキストファイル内の複数行の文字列を検索したいと考えています。 私はInStrの機能を使用しようとしました。私の正確な目的は、セルに格納されている複数行の文字列を読み込み、それがテキストファイルで利用可能かどうかをチェックすることです。そのために、テキストファイルを変数に読み込み、セルに保存された文字列を別の変数に読み込み、バイナリ比較を使ってInstrを使って比較します。 InStrは複数行の文字列で動作しますか?それを比較する他の方法がない場合は?私は、文字列が同一であるものの、identical.Evenているように見える、検索結果は常に失敗の両方の文字列をチェックするとVBAは複数行の検索に威力を発揮します

これは私のコード

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 

です。どんな提案も参考になります。

+0

行を連結してみましたか? – KyloRen

+1

Excelセル内の複数行の文字列は、通常、行分離記号として 'vbLf'(ASCII 10)を持ちます。テキストファイル(Windowsの場合)は通常、 'vbCrLf'(ASCII 13 + ASCII 10)です。 Instr()を使用すると一致しません。したがって、Instr()を使用する前にセルのテキストの 'vbLf'を' vbCrLf'に置き換えることができます。 –

+0

@TimWilliamsの示唆したように、 'InStr'関数を使う前に、 – 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 
関連する問題