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

我试图创build一个函数:

  • 以一个单元格作为参数
  • 看看是否该单元格在列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 

谢谢

尝试一下-

 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 

您也可以使用Range.Findfunction。 (我不知道什么更快)

例如:

 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