我正在尝试从结果之前的行修改中删除行。我试图使用Find命令,但我没有运气。这是我尝试过的众多变种之一:
Sub FindandDelete()
Modifications = Range("A1:A1200").Find("Modifications", LookIn:=xlValues)
Res = Cells.Find("Results", LookIn:=xlValues)
Range("Modifications:Results").Delete
End Sub
有任何想法或建议吗?
答案 0 :(得分:1)
您的代码无效的两个主要原因:
所以你走了:
Sub FindandDelete()
Modifications = Range("A1:A1200").Find("Modifications", LookIn:=xlValues).Row
Res = Cells.Find("Results", LookIn:=xlValues).Row
Range(Modifications & ":" & Res).Delete
End Sub
但如果找不到值,则会抛出错误...
所以试试这个更精细但更准确的技术:
Sub SomeSub()
'Just to stay clean and make sure we're using the proper workbook/sheet
wb = ThisWorkbook
ws = wb.Sheets("YourSheet") 'Rename with your sheet's name
columnOfInterest = 1 'Replace with the number of the column
'Find the last row of that column
last = ws.Cells(ws.Rows.Count, columnOfInterest).End(xlUp).Row
'Loop from the first row to the last...
For x = 1 To last
'And stop at the first thing that resembles "Results"...
If ws.Cells(x, columnOfInterest) Like "*Results*" Then
Res = x
Exit For
End If
Next x
'Loop from the first row to the last...
For x = 1 To last
'And stop at the first thing that resembles "Modifications"...
If ws.Cells(x, columnOfInterest) Like "*Modifications*" Then
Modif = x
Exit For
End If
Next x
If Res > 0 And Modif > 0 And Res > Modif Then
'Loop from "Results" to "Modifications" (backwards, indeed) to delete the rows
For x = Res To Modif Step -1
ws.Rows(x).Delete
Next x
End If
End Sub
答案 1 :(得分:0)
试试这个:
Sub FindandDelete()
Dim Modifications As Excel.Range
Dim Res As Excel.Range
Set Modifications = Range("A1:A1200").Find(What:="Modifications", LookIn:=xlValues)
Set Res = Range("A1:A1200").Find(What:="Results", LookIn:=xlValues)
If Not (Modifications Is Nothing) And Not (Res Is Nothing) Then
ActiveSheet.Range(Modifications, Res).EntireRow.Delete 'ClearContents '<<edit to delete rows rather than just clear their contents
End If
End Sub
使用行号略有不同:
Sub FindandDeleteRows()
Dim Modifications As Integer
Dim Res As Integer
Dim lookinRange As Range
Set lookinRange = Excel.ThisWorkbook.ActiveSheet.Range("A1:A1200")
If Not (lookinRange.Find(What:="Modifications", LookIn:=xlValues) Is Nothing) Then
Modifications = lookinRange.Find(What:="Modifications", LookIn:=xlValues).Row
End If
If Not (lookinRange.Find(What:="Results", LookIn:=xlValues) Is Nothing) Then
Res = lookinRange.Find(What:="Results", LookIn:=xlValues).Row
End If
ActiveSheet.Rows(Modifications & ":" & Res).ClearContents
End Sub