[ 初めての方へ | 一覧(最新更新順) | 全文検索 | 過去ログ ]
『テキストファイル内の文字列を検索』(hiro)
題記の件についてご相談させていただきます。
以下のような処理を行うプログラムを書きたいのですが、
どのような書いたら良いかわからず困っております。
どなたかご教示お願いします。
1
テキスファイルを読み込む
2
エクセルのシート1のキーワードを検索
例
アイス
ケーキ
ジュース
などがシートに貼り付けられております。
3検索キーワードがあれば隣に○なければ✖を記載したい。
< 使用 Excel:unknown、使用 OS:unknown >
(ひまつぶし) 2021/10/29(金) 15:57
Dim Buf As String Dim STR As String Dim Lost_Row As String
Dim Directory As String
Dim str1 As String Dim str2 As String
Dim i As Long ' インデックス用の変数
'最終行を所得 Lost_Row = Cells(1, 1).End(xlDown).Row
Debug.Print InputBox(Lost_Row)
i = 1
'検索ワード STR = Cells(i, 1)
Close #1 'デバッグ用
'この階層を変数で定義したいです。
Open "C:\Users\tamur\Desktop\555\putty.txt" For Input As #1
'Open Directory For Input As #1
'データが無くなるまで繰り返す
For i = 1 To Lost_Row
'ヘッダー行を無視したいため1行目を予め無駄に読み込む Line Input #1, Buf
Do Until EOF(1) Line Input #1, Buf If InStr(Buf, STR) <> 0 Then Debug.Print InputBox("OK") '見つけた時点で終了 Cells(i, 2) = "○" GoTo Continue
'見つからなかったので次の行 Else Cells(i, 2) = "×" 'B列に×を記載 End If Loop
Continue:
'Debug.Print InputBox(i) Next
Close #1 End Sub
(hiro) 2021/10/29(金) 18:25
結構面倒ですよ 検索するワード数×テキストファイルの行数 だけ Instrで調べないといけないです 2重ループ二なりますが、 (a) 1行読んだら全ワードを検索して、行数分繰り返す か (b) 1行読んだら1ワードを検索して、行末までいったら、1行目に戻って、次のワードを繰り返す どっちもアリです。
質問者さんのコードでは、(b)でやってるようですが、 テキストファイルの1行目に戻すコードがありません 以下のサンプルは、(a)でやってます。 Sub sample() Dim buf As Variant Dim Dic As Object Dim fn As Long, line As String With ActiveSheet With .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp)) .Offset(, 1).Value = "×" buf = .Resize(, 2).Value End With End With Set Dic = CreateObject("Scripting.Dictionary") For i = LBound(buf) To UBound(buf) If Not Dic.Exists(buf(i, 1)) Then Dic.Add buf(i, 1), i End If Next fn = FreeFile Open "D:\test.txt" For Input As fn Line Input #fn, line Do While Not EOF(fn) Line Input #fn, line For Each s In Dic If InStr(line, s) Then buf(Dic(s), 2) = "○" Dic.Remove s End If If Dic.Count = 0 Then Exit Do Next Loop Close fn ActiveSheet.Cells(1, 1).Resize(UBound(buf), 2).Value = buf End Sub (´・ω・`) 2021/10/29(金) 21:12
[ 一覧(最新更新順) ]
YukiWiki 1.6.7 Copyright (C) 2000,2001 by Hiroshi Yuki.
Modified by kazu.