传递范围名称

时间:2015-06-19 06:06:53

标签: excel excel-vba vba

我定义了几个范围,例如:

Sheets(“Customers”).Activate
Set MYR1 = Range(Cells(1,  1), Cells(1,  25))
Set MYR2 = Range(Cells(5,  1), Cells(5,  25))
Set MYR2 = Range(Cells(16,  1), Cells(16,  25))

在另一个程序中,我编写了以下代码来搜索范围并处理结果。我的问题是如何调用Findany例程并根据需要传递不同的范围。

Sub Findany()
    Set foundrange =  MYR1.Find(what:=i)
    If foundrange Is Nothing Then
        Do Something
    Else
        Do Something Else
    End if

2 个答案:

答案 0 :(得分:0)

我认为你需要这样的东西:

Sub Findany(rngToSearchIn As Range)    '<< argument in this line

    Set foundrange = rngToSearchIn.Find(what:=i)    '<<passed range used here
    If foundrange Is Nothing Then
        Do Something
    Else
        Do Something Else
    End If

调用Findany soubroutine时请使用:

Call Findany(MYR1)

或简单地说:

Findany MYR1

答案 1 :(得分:0)

使用功能可能更容易:

Function Range1() As Range
    Set Range1 = Range("A1:C3")
End Function

另一个范围:

Function Range2() As Range
    Set Range2 = Range("A5:C7")
End Function

等等......

然后是Findany子:

Sub Findany(rng As Range, query As String)
    Set foundrange = rng.find(what:=query)
    If foundrange Is Nothing Then
        MsgBox "not found!"
    Else
        MsgBox "found"
    End If
End Sub

最后:

Sub Search()
Call Findany(Range2, "hello")
End Sub

完成!