2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【ExcelVBA】レコードデータが全て「0」判定を配列で行い、レコード1件(行)削除する処理

Last updated at Posted at 2025-02-18

はじめに

無駄な変数を定義するより、配列を使ってレコードデータが全て「0」判定を実施する処理を実装することにしました。

用意したデータ

用意したデータは下記のとおりです。

before.jpg

実装したソースコード

実装したソースコードは下記になります。

'配列を使い、配列の要素が全て0のデータを削除する処理
Sub arraytest()
    'ワークシート変数の定義
    Dim ws1 As Worksheet
    '範囲変数の定義
    Dim r As range
    '配列の定義
    Dim array1 As Variant
    'カウント計算の変数
    Dim count As Long
    'カウント変数
    Dim i As Long
    '配列の要素データの変数
    Dim data As Variant
    '最終行変数
    Dim last_row_num As Long
    
    'ws1変数をセット
    Set ws1 = ThisWorkbook.Worksheets("Sheet1")
    '最終行を取得
    last_row_num = ws1.Cells(Rows.count, 2).End(xlUp).Row
    'カウント変数(開始行の行数)をセット
    i = 3
    'カウント変数が最終行の行数を超えるまでループする
    While i <= last_row_num
        count = 0
        Set r = ws1.range("C" & i & ":" & "E" & i)
        array1 = r
        '配列の要素を取り出し、要素が0の個数を計算する
        For Each data In array1
            If data = 0 Then
                count = count + 1
            End If
        Next
        '0の個数が3の時、行削除する
        If count = 3 Then
            ws1.Rows(i).Delete
            
        Else
        '違う場合はカウント変数を1足す
            i = i + 1
        End If
        
        '最終行を取得する
        last_row_num = ws1.Cells(Rows.count, 2).End(xlUp).Row
        
    Wend
    
End Sub
    

実行した結果

実行した結果は下記になります。

after.jpg

最後に

配列を使った判定を使うと、コーディングが楽ですね。

2
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?