How to select a range of rows using two variables in VBA

半城伤御伤魂 提交于 2019-12-04 20:09:26
Santosh

Your code can be re-written as below. Avoid using Select in your code. Check this link to know why.

Sub SelectConsultantData()
    Dim Consultant1 As Integer, Consultant2 As Integer
    Dim ConsultantRange As Range

    Dim rngFind As Range
    Set rngFind = Columns("A:A").Find(What:="Andrew", After:=Range("A1"), LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext)

    If Not rngFind Is Nothing Then
        Consultant1 = rngFind.Row + 1
    End If

    Set rngFind = Columns("A:A").Find(What:="Bob", After:=Range("A1"), LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext)

    If Not rngFind Is Nothing Then
        Consultant2 = rngFind.Row - 1
    End If

    If Consultant1 > 0 And Consultant2 > 0 Then
        Set ConsultantRange = Range(Cells(Consultant1, 2), Cells(Consultant2, 6))
    End If

End Sub
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!