我有一个包含9列的数据集。我想检查每一行,看看最后3列是否为空。如果3个都是空的,我想删除该行。我目前正尝试在VBA中实现这一点,但我是一个编程新手,我发现自己完全不知所措。
我写的伪代码如下:
For Row i
If(Col 1 & Col 2 & Col 3) = blank
Then delete Row i
Move on to next Row
发布于 2017-02-24 01:50:08
我会像下面这样
Dim iArea As Long
With Range("E:G") '<--| change "E:G" to your actual last three columns indexes
If WorksheetFunction.CountBlank(.Cells) < 3 Then Exit Sub
With .SpecialCells(xlCellTypeBlanks)
For iArea = .Areas.Count To 1 Step -1
If .Areas(iArea).Count Mod 3 = 0 Then .Areas(iArea).EntireRow.Delete
Next
End With
End With
发布于 2017-02-24 00:13:03
假设您至少有一行总是被填写,您可以使用以下命令:
Dim LR as Long
Dim i as Integer
LR = Cells(Sheets("REF").Rows.Count,1).End(xlUp).Row
For i = 1 to 9
If Range(Cells(LR-3,i),(Cells(LR,i)).Value="" Then
Columns(i).Delete
Else:
End If
Next i
这是通过将最后一行定义为LR,并将一个变量定义为i。您将检查列"i“以确定该列的最后3行是否为"",也就是它是否为空;您可以尝试使用ISBLANK(),但这不适用于数组。如果这是真的,那么您将删除列i。然后代码将移动到下一个i。使用i的FOR循环从1开始到9,这对应于从第1 (A)列开始并在第9 (I)列结束。
编辑:
我似乎误读了应该是空的,应该删除的,就列/行而言……这段代码将被重写为:
Dim LR as Long
Dim i as Integer
LR = Cells(Sheets("REF").Rows.Count,1).End(xlUp).Row
For i = LR to 2 Step -1 'Assumes you have headers in Row1
If AND(ISBLANK(Cells(i,7)),ISBLANK(Cells(i,8)),ISBLANK(Cells(i,9)) Then
Rows(i).Delete
End If
Next i
重要的更改是检查行中最后3列中的每一列都为空,ISBLANK(),更改满足条件时删除行,以及更改循环通过的内容。
发布于 2017-02-24 00:19:26
这是另一个答案,假设你的最后三列以"G","H","I“开头。
Sub DeleteRowWithLastThreeColumnsBlank()
Dim N As Long, i As Long
N = Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To N
If Cells(i, "G").Value = "" And Cells(i, "H").Value = "" And Cells(i, "I").Value = "" Then
Rows(i).EntireRow.Delete
N = Cells(Rows.Count, "A").End(xlUp).Row
End If
Next i
End Sub
https://stackoverflow.com/questions/42420668
复制相似问题