我想在Excel(2003)中获取导入的数据转储并将其格式化为报表。我所做的大部分工作都涉及录制宏,然后根据需要自定义代码。我有一个需要纯代码的地方。
我有一个SORTED列(D)列出了事件类型(例如:车辆火灾,中风,动物咬伤等)。我想读取D列中的每个值,如果它不是我们要查找的几个值中的一个,则删除整行。
我尝试过多个版本的代码(我在网上找到),产生最接近我需要的结果的代码如下:
Range("D:D").Select
Dim workrange As Range
Dim cell As Range
Set workrange = Intersect(Selection, ActiveSheet.UsedRange)
For Each cell In workrange
If ActiveCell.Value <> "VFIRE" _
And ActiveCell.Value <> "ILBURN" _
And ActiveCell.Value <> "SMOKEA" _
And ActiveCell.Value <> "ST3" _
And ActiveCell.Value <> "TA1PED" _
And ActiveCell.Value <> "UN1" _
Then ActiveCell.EntireRow.Delete
Next cell
End Sub
此代码删除列表的大部分(原始168的约100行),但它只删除行,直到它达到我想要的第一个值。例如,此当前数据转储没有&#34; ILBURN&#34;的任何值。或&#34; SMOKEA&#34;,但是当第一次出现&#34; ST3&#34;发生宏停止。没有产生错误,它似乎认为它已经完成。
我应该添加什么来通过整个列表调用宏?
答案 0 :(得分:5)
我只是简洁。
Sub DeleteRowBasedOnCriteria()
Dim RowToTest As Long
For RowToTest = Cells(Rows.Count, 4).End(xlUp).Row To 2 Step -1
With Cells(RowToTest, 4)
If .Value <> "VFIRE" _
And .Value <> "ILBURN" _
And .Value <> "SMOKEA" _
And .Value <> "ST3" _
And .Value <> "TA1PED" _
And .Value <> "UN1" _
Then _
Rows(RowToTest).EntireRow.Delete
End With
Next RowToTest
End Sub
答案 1 :(得分:0)
我同意@Tim_Williams你需要向后工作,因为这似乎是个问题。我会做这样的事情。
Sub Main()
Dim workrange As Range
Dim Firstrow As Integer
Dim Lastrow As Integer
Dim lrow As Integer
'Find first and last used row in column D
Range("D:D").Select
Firstrow = ActiveSheet.UsedRange.Cells(1).Row
Lastrow = ActiveSheet.Range("D1").Offset(Sheet1.Rows.Count - 1, 0).End(xlUp).Row
'Loop through used cells backwards and delete if needed
For lrow = Lastrow To Firstrow Step -1
Set workrange = Cells(lrow, 4)
If workrange.Value <> "VFIRE" _
And workrange.Value <> "ILBURN" _
And workrange.Value <> "SMOKEA" _
And workrange.Value <> "ST3" _
And workrange.Value <> "TA1PED" _
And workrange.Value <> "UN1" _
Then workrange.EntireRow.Delete
Next lrow
End Sub
答案 2 :(得分:0)
我在我的一个任务中使用了这个,因为我有100次迭代的测试数据阵列,我想修剪到前10次迭代,所以我使用“迭代#&gt; 10”单元格来删除整行
Sub trim_row()
' trim_row Macro
' to trim row which is greater than iteration#10
Dim RowToTest As Long
Dim temp As String
Dim temp1 As Integer
For RowToTest = Cells(Rows.Count, 6).End(xlUp).Row To 2 Step -1
With Cells(RowToTest, 6)
temp = .Value
If temp = "" Then
Else
temp1 = Trim(Replace(temp, "Iteration# :: ", ""))
If temp1 > 10 Then
Rows(RowToTest).EntireRow.Delete
End If
End If
End With
Next RowToTest
End Sub
我是用户替换&amp;从字符串中提取数字的行程,并引入if =“”条件以跳过空行。我将空行分隔为测试数据集。