查找字符串,选择该行及其上方的所有行

时间:2016-06-05 23:41:11

标签: excel vba excel-vba select

我正在尝试从我的工作表顶部选择一个范围(列A:E),直到单词“Grand Total”,包括这些单词出现的行。然后我想复制该范围并将其粘贴到一个不同的工作表。到目前为止我找到“Grand Total”的代码是,但它不起作用:

Sub QuickFind()
Dim rng1 As Range
Dim strFind As String
strFind = "Grand Total"
Set rng1 = ActiveSheet.Cols("A").Find(strFind, , xlValues, xlWhole)
If rng1 Is Nothing Then
    MsgBox strFind & " not found"
Else
    Range(rng1, rng1.End(xlDown)).Activate
End If
End Sub

我是从某个地方复制过的,它说ActiveSheet.Rows(1)。它似乎不喜欢我如何将其更改为ActiveSheet.Cols("A")

3 个答案:

答案 0 :(得分:0)

这个小小的变化:

Sub QuickFind()
    Dim rng1 As Range
    Dim strFind As String

    strFind = "Grand Total"
    Set rng1 = ActiveSheet.Range("A:A").Find(strFind, , xlValues, xlWhole)
    If rng1 Is Nothing Then
        MsgBox strFind & " not found"
    Else
        Range(rng1, rng1.End(xlDown)).Activate
    End If
End Sub

将从“Grand Total”到其下方的内容中选择所有内容:

enter image description here


注意:

选择向下而不是向上。

答案 1 :(得分:0)

Sub QuickFind()

Dim rng1 As Range

Dim theRngWhereYouWantToPaste As Range

'将下面的范围更改为您想要的范围

设置TheRngWhereYouWantToPaste = ActiveSheet.Columns(“F:J”)

Dim strFind As String

strFind =“Grand Total”

设置rng1 = ActiveSheet.Columns(“A”)。查找(strFind,xlValues,xlWhole)

如果rng1没什么,那么

MsgBox strFind& “没找到”

否则

范围(“A1:E”& rng1.Row)。复制目的地:= theRngWhereYouWantToPaste

结束如果

End Sub

答案 2 :(得分:0)

是否要将ACED Sheet中的范围从第1行复制/粘贴到" Grand Total"可以在#34; A"列中找到,然后你可以使用它:

Option Explicit

Sub QuickFind()
    Dim rng1 As Range
    Dim strFind As String

    strFind = "Grand Total"

    With ActiveSheet
        Set rng1 = .Range("A:A").Find(strFind, , xlValues, xlWhole)
        If rng1 Is Nothing Then
            MsgBox strFind & " not found"
        Else
            .Range("A:E").Resize(rng1.Row).Copy Destination:=Worksheets("different worksheet").Range("A1") '<~~ change "different worksheet" with actual name of the worksheet you want to paste to
        End If
    End With
End Sub

如果您对复制值感兴趣,请替换:

            .Range("A:E").Resize(rng1.Row).Copy Destination:=Worksheets("different worksheet").Range("A1") '<~~ change "different worksheet" with actual name of the worksheet you want to paste to

使用:

            Worksheets("different worksheet").Range("A1").Resize(rng1.Row, 5).Value = .Range("A:E").Resize(rng1.Row).Value '<~~ change "different worksheet" with actual name of the worksheet you want to paste to