如何在Excel中使用特定文本选择行前后的行?

时间:2017-11-20 22:06:04

标签: excel

我的原始数据看起来像这样;

std1
std1
deviant
std2
std1
std2
std2
deviant

“deviants”随机呈现,因此不会每第n行出现......

我希望在每个“异常”行之前选择1行和1行,以便我可以将其复制到另一张电子表格中。

2 个答案:

答案 0 :(得分:0)

见下面的代码。

我们循环遍历列中的每一行(我假设您的数据在A列中),当找到给定值时,我们将以下和之前的行添加到我们的选择数组中。循环完成后,我们选择数组中的行

Public Sub DeviantSelect()

    Dim myRange As Range
    Set myRange = Nothing
    lastRow = Cells(Rows.Count, "A").End(xlUp).Row

    For i = 1 To lastRow
        If Cells(i, 1) = "deviant" Then
            If myRange Is Nothing Then
                Set myRange = Union(Range(i - 1 & ":" & i - 1), Range(i + 1 & ":" & i + 1))
            Else
                Set myRange = Union(myRange, Range(i - 1 & ":" & i - 1), Range(i + 1 & ":" & i + 1))
            End If
            myRange.Select
        End If
    Next

End Sub

答案 1 :(得分:0)

以下代码将异常之前和之后的单元格复制到另一张表格。

    Sub check()
Sheet1.Activate
Range("A1").Select

 LastRow = Sheets("Sheet1").UsedRange.Rows(Sheets("Sheet1").UsedRange.Rows.Count).Row

For i = 1 To LastRow
Sheet1.Activate

If Range("A" & i).Value = "deviant" Then
Range("A" & i - 1).Select
Selection.Copy
Sheet2.Activate
 LastRow2 = Sheets("Sheet2").UsedRange.Rows(Sheets("Sheet2").UsedRange.Rows.Count).Row
 If LastRow2 = 1 Then
 Range("A" & LastRow2).Activate
 Else
 Range("A" & LastRow2 + 1).Activate
 End If
ActiveSheet.Paste

Sheet1.Activate
Range("A" & i + 1).Select
Selection.Copy
Sheet2.Activate
 LastRow2 = Sheets("Sheet2").UsedRange.Rows(Sheets("Sheet2").UsedRange.Rows.Count).Row
 Range("A" & LastRow2 + 1).Activate
ActiveSheet.Paste

End If

Next

End Sub
相关问题