ファイルから特定の文字列を検索する

◆概要

このページは、Visual Basic 6.0で、テキストファイルから特定の文字列を検索する方法について記載しています。


テキストファイルから順次データを読み込み、読み込むたびにデータから文字列を検索することで実現できます。

◆Sample code

フォームに検索文字を入力するText1、検索結果を表示するText2、Text1の上にCaptionが"検索する文字列"とするLabel1、Text2の上に検索結果の行と列を表示するLabel2を配置します。

フォームの設計

次のコードを入力します。

フォームモジュール

Option Explicit

Private Function SearchString(strRecBuff As String, _
                            intRowCounter As Integer, _
                            intColCounter As Integer) As Boolean


    Dim intFindPos As Integer
   
    'プロシージャの既定の戻り値を設定
    SearchString = False

    '引数strRecBuffからテキストボックスの文字列を検索
    intFindPos = InStr(strRecBuff, Text1.Text)

    '検索文字列が見つかったら
    If intFindPos > 0 Then
        'ラベルに、ファイルの位置を表示
        Label2.Caption = "行 = " & _
                        CStr(intRowCounter) & _
                        ",カラム= " & _
                        CStr(intColCounter)

        '検索した文字列を含むデータを表示し、
        '検索した文字列をハイライト表示
        With Text2
            .Text = strRecBuff
            .SelStart = intFindPos - 1
            .SelLength = Len(Text1.Text)
        End With

        '検索文字列が見つかったら戻り値をFalseに設定する
        SearchString = True
    End If

End Function


Private Sub Command1_Click()
    Dim strFileName As String
    Dim strRecBuff As String
    Dim intFileNo As Integer
    Dim intColCounter As Integer
    Dim intRowCounter As Integer
   
    Label2.Caption = ""

    '読み込むCSVファイル名
    strFileName = "C:\Readme.txt"
    
    '空いているファイル番号を取得
    intFileNo = FreeFile

    'ファイルを開く
    Open strFileName For Input As intFileNo

    'ファイルの最後に達するまでループ
    Do Until EOF(intFileNo)

        'ファイルの行数をカウント
        intRowCounter = intRowCounter + 1

        '1行分のデータを読み込む
        For intColCounter = 1 To 5
            'ファイルから読み込んだ内容を変数に保存
            Input #intFileNo, strRecBuff
            '検索文字列が見つかったらループを抜ける
            If SearchString(strRecBuff, _
                            intRowCounter, _
                            intColCounter) Then
                    Exit Do
            End If
        Next
    Loop

    '検索文字列が見つからなかった場合の表示
    If Label2.Caption = "" Then
        Text2.Text = "検索文字列は見つかりませんでした。"
    End If

    'ファイルを閉じる
    Close intFileNo

End Sub


▼ページトップへ