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

时间:2015-12-15 01:42:03

标签: excel vba excel-vba user-defined-functions udf

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

此函数搜索工作表(工作表名称)以查看是否可以在任何列中找到输入值,如果是,则返回列的第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

1 个答案:

答案 0 :(得分:0)

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

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