简体   繁体   中英

Excel VBA Find function not returning an integer value, can't see what I am doing wrong

so I am writing an excel marco to automate some manual tasks. I've hit a wall in a function I am writing, it fails to return a integer value to me for use in the sub I am calling it from. I feel like this is simple but I can't for the life of me see what I am doing wrongly.

Function Find_Header(SearchTerm As String) As Integer
Dim Rng As Range
With Sheets("DATA").Range("A:CZ")
    Set Rng = .Find(What:=SearchTerm, _
                    After:=.Cells(.Cells.Count), _
                    LookIn:=xlValues, _
                    lookat:=xlWhole, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlNext, _
                    MatchCase:=False)
    If Not Rng Is Nothing Then
        Application.Goto Rng, True
        Find_Header = Rng.Column
    Else
        MsgBox "Nothing found"
    End If
End With
End Function

From witin a sub I call it thusly:

Find_Header SearchTerm:="Status"

And since the term 'Status' is within the range specific and is Column number 5 I expect to see 'Find_Header' is equal to 5 within my sub, however as soon as the function ends the variable is lost, what I am not doing to retain this value in the sub routine?

Thanks, Chris

You need to store the result in a variable - for example:

Dim iFoundCol as Integer
iFoundCol = Find_Header(SearchTerm:="Status")

函数返回一个需要存储在变量中的值,您不能只是简单地调用该函数

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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