Excel UDF在通过sub调用时工作,但始终在工作表中返回0

我的函数在工作表中被调用时总是返回0,但是当通过子调用时返回正确的值。

此函数search工作表(sheetname),查看是否可以在任何列中findinput值,如果是,则返回列的第1行中的值。

'test sub Sub test() MsgBox custCat("SUNTRUST BANK") End Sub Public Function custCat(toSearch) Dim sheetName As String sheetName = "LookupValues" Dim i As Integer i = 1 Dim lastRow As Integer Dim colLtr As String Dim j As Integer 'find last column Dim lastColumn As Integer lastColumn = Worksheets(sheetName).Range("A1").SpecialCells(xlCellTypeLastCell).Column 'loop through columns Do While i <= lastColumn 'find last row lastRow = Worksheets(sheetName).Cells(Worksheets(sheetName).Rows.Count, i).End(xlUp).Row 'search through column j = 2 Do While j <= lastRow If InStr(UCase(toSearch), UCase(Worksheets(sheetName).Cells(j, i).Value)) > 0 Then If custCat = "" Then custCat = Worksheets(sheetName).Cells(1, i).Value Else custCat = custCat & ", " & Worksheets(sheetName).Cells(1, i).Value End If j = lastRow 'exit loop if found End If j = j + 1 Loop i = i + 1 Loop End Function 

我清理了一下代码并做了一些调整,试试这个:

 Public Function custCat(toSearch) Dim i&, j&, lastRow&, lastColumn& Dim ws As Worksheet Set ws = Worksheets("LookupValues") With ws lastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column i = 1 'loop through columns Do While i <= lastColumn 'find last row lastRow = .Cells(.Rows.Count, i).End(xlUp).Row 'search through column j = 2 Do While j <= lastRow If InStr(UCase(toSearch), UCase(.Cells(j, i).Value)) > 0 Then If custCat = "" Then custCat = .Cells(1, i).Value Else custCat = custCat & ", " & .Cells(1, i).Value End If Exit Do 'exit loop if found End If j = j + 1 Loop i = i + 1 Loop End With End Function