函数循环遍历所有工作表以查找值,返回工作表名称

时间:2017-06-19 18:50:43

标签: excel vba excel-vba

我正在尝试创建一个函数:

  • 将一个单元格作为参数
  • 查看单元格是否在A列中
    • 如果为true,则返回工作表名称
    • 如果为false,则移至下一个工作表并再次尝试

我尝试过几种不同的方式,但我无法让它发挥作用。目前,这就是我所在的地方:

Option Explicit

Public Function codeLookup(cellOne)

    Dim ws As Worksheet
    Dim findValue As Boolean

    With WorksheetFunction
        findValue = .VLookup(cellOne, ws.Range("A:A"), 1)
    End With

    For Each ws In ActiveWorkbook.Worksheets
       If findValue = True Then
       codeLookup = Application.Caller.Worksheet.Name
       End If
       Next

End Function

谢谢

2 个答案:

答案 0 :(得分:2)

试一试 -

Public Function codeLookup(cellOne)

Dim ws As Worksheet
Dim findValue As Variant

On Error Resume Next
For Each ws In ActiveWorkbook.Worksheets
findValue = WorksheetFunction.VLookup(cellOne, ws.Range("A:A"), 1)
   If findValue <> "" Then
   codeLookup = ws.Name
   Exit Function
   End If
Next

End Function

答案 1 :(得分:1)

您还可以使用Range.Find函数。 (我不知道什么更快)

例如:

Public Function codeLookup(cellOne) As String

    Dim ws As Worksheet
    Dim searchRange As Range

    For Each ws In ActiveWorkbook.Worksheets
        Set searchRange = ws.Columns(1).Find(what:=cellOne, LookIn:=xlValues)
        If Not searchRange Is Nothing Then
            codeLookup = ws.Name
            Exit Function
        End If
    Next
    codeLookup = "No match found"
End Function