アンケート一覧ページでアンケートを探す

エクセルのマクロで、指定した複数の文字列(いずれでもあれば)含むその行を削除させるにはどうしたらよいでしょうか?

Visual Basic16,350閲覧xmlns="http://www.w3.org/2000/svg">50

新機能 AI回答テストを実施中! テスト対象カテゴリ:歴史・悩み相談 ※回答がつかない場合は、画面のリロードをお試しください

ベストアンサー

NEW! この回答はいかがでしたか? リアクションしてみよう

ThanksImg質問者からのお礼コメント

皆様ありがとうございます。 正直に言いますと知識がないもので、どれが優秀なものか判断がつきかねました。 ただ、見も知らぬ人間に対しての皆様の親切なご対応のおかげで処理がだいぶ進みました。 ありがとうございました。

お礼日時:2011/8/20 17:09

その他の回答(3件)

takebashi123さん コードの変更は最小限にしていますが 少しコードの順番を入れ替えることにより処理速度が上がります 最初に最終行を求めてしまうと 処理列が進むにつれて行が削除されているため 削除された行分だけ処理に無駄が出てきます 処理列が代わるたびに最終行を取得する事によりこれを回避しています Sub test3() Dim strWord As Variant Dim i As Long, LastRow As Long Dim j As Long, LastCol As Long Dim z As Integer '文字列を指定する strWord = Split("test,test2,test3", ",") 'A1セルを基準に LastCol = Cells(1, 1).SpecialCells(xlLastCell).Column '最終列を取得 '列数分繰り返す For j = 1 To LastCol '行数分繰り返す LastRow = Cells(Rows.Count, j).End(xlUp).Row '処理列の最終行を取得 For i = LastRow To 1 Step -1 '最終行から1行目まで '指定文字列を含んでいたら For z = 0 To UBound(strWord) If InStr(Cells(i, j).Value, strWord(z)) <> 0 Then Rows(i).Delete Shift:=xlUp '削除 Exit For End If Next z Next i Next j End Sub 参考まで

色々やり方ありますが以下一例 Sub Macro1() Dim strWord(10) As String 'とりあえずキーワード10個分 Dim i As Long, LastRow As Long Dim j As Long, LastCol As Long Dim cnt As Integer '文字列を指定する strWord(0) = "test" strWord(1) = "test2" strWord(2) = "test3" strWord(3) = "test4" strWord(4) = ""'キーワードの最後 'A1セルを基準に LastRow = Cells(1, 1).SpecialCells(xlLastCell).Row '最終行を取得 LastCol = Cells(1, 1).SpecialCells(xlLastCell).Column '最終列を取得 '行数分繰り返す For i = LastRow To 1 Step -1 '最終行から1行目まで '列数分繰り返す For j = 1 To LastCol '指定文字列を含んでいたら cnt = 0 Do Until strWord(cnt) = "" If InStr(Cells(i, j), strWord(cnt)) <> 0 Then Rows(i).Delete Shift:=xlUp '削除 Exit For End If cnt = cnt + 1 Loop Next j Next i End Sub とりあえずキーワードが空白になるまでループしてますが数が固定ならDO LOOPの代わりにその分FOR文で回すとかIF、ELSEIFとかセレクト、ケース命令使うとか色々あります

なるべく現在のコードを利用する形で書いてみました。 Sub testqq() Dim strWord As String Dim i As Long, LastRow As Long Dim j As Long, LastCol As Long Dim Dstr As Variant, Dflg As Boolean, kk As Long '文字列を指定する strWord = "test,abc,aremo,koremo,soremo" Dstr = Split(strWord, ",") 'A1セルを基準に LastRow = Cells(1, 1).SpecialCells(xlLastCell).Row '最終行を取得 LastCol = Cells(1, 1).SpecialCells(xlLastCell).Column '最終列を取得 '行数分繰り返す For i = LastRow To 1 Step -1 '最終行から1行目まで Dflg = False '列数分繰り返す For j = 1 To LastCol For kk = 0 To UBound(Dstr) If InStr(Cells(i, j), Dstr(kk)) <> 0 Then Dflg = True Exit For End If Next If Dflg = True Then Exit For Next j If Dflg = True Then Rows(i).Delete Shift:=xlUp '削除 Next i End Sub 1 削除のキーワードはvariant変数に配列として入れる。(Split関数を使いました。)こうすることで比較にLoopが使える。 2 削除するかどうかのDflgという変数を使い1行分の終わりの処理で削除するようにした。