繁体   English   中英

Excel VBA选择一个单元格区域,直到一个单元格包含特定文本

[英]Excel VBA Select a Range of Cells Until a Cell Contains Specific Text

我已经能够在工作表中搜索名称(下面的代码中为Dion),然后将包含名称Dion的行复制到另一个工作表中。 但是,目标工作表中的文本可能与源工作表中的最后一列相邻,甚至超出。

我希望能够从包含Dion的行中选择一个单元格范围,而选择的结尾是包含特定文本的单元格。

我还尝试将If Cells(...).Value = "Dion" Then更改为If Range("A1:CS1000")...但始终收到类型不匹配错误。

这是我的VBA代码。 我知道这可能效率很低,但这是我能够完成的工作:

Dim r As Long
Dim endRow As Long
Dim pasteRowIndex As Long

Worksheets("Tracking").Activate

endRow = 500
pasteRowIndex = 1

For r = 6 To endRow

    If Cells(r, Columns("BM").Column).Value = "Dion" Then

        Rows(r).Select
        'Code above shoud select all cells from Rows(r) until a cell contains the text "End"
        Selection.Copy

        Worksheets("Dion").Select
        Rows(pasteRowIndex + 5).Select
        ActiveSheet.Paste

        pasteRowIndex = pasteRowIndex + 1

        Worksheets("Tracking").Select

    End If

Next r

谢谢你的帮助。

如果您只是试图将行的副本限制为最多包含“ End”值的列,则以下代码应该有效:

Dim r As Long
Dim endRow As Long
Dim pasteRowIndex As Long
Dim endCell As Range

'Use With block so that we can write '.' instead of 'Worksheets("Tracking").'
With Worksheets("Tracking")

    endRow = 500
    pasteRowIndex = 1

    For r = 6 To endRow
        'Always qualify 'Cells', 'Range', 'Columns' and 'Rows' objects so that we
        'know what sheet we are referring to
        'Also, as pointed out by A.S.H, ' Columns("BM").Column ' can be
        'shortened to ' "BM" '
        If .Cells(r, "BM").Value = "Dion" Then
            'Find, in the current row, the location of the first cell containing "End"
            'Note: If you want to search for the word "End" by itself, rather than just
            '"End" within the cell (e.g. in the value "Endymion"), change "xlPart" to
            '"xlWhole"
            Set endCell = .Rows(r).Find(What:="End", LookIn:=xlValues, LookAt:=xlPart, After:=.Cells(r, "A"))
            If endCell Is Nothing Then
                'If no "End" found, copy the entire row
                .Rows(r).Copy Worksheets("Dion").Rows(pasteRowIndex + 5)
            Else
                'If "End" found, copy from column A to the cell containing "End"
                'Note: I have assumed you don't want to copy the "End" cell itself
                .Range(.Cells(r, "A"), endCell.Offset(0, -1)).Copy Worksheets("Dion").Rows(pasteRowIndex + 5).Cells(1, "A")
            End If

            pasteRowIndex = pasteRowIndex + 1

        End If

    Next r
End With

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM