VBA:在工作表中的UDF地址上应用MAX

时间:2018-01-02 17:06:08

标签: excel excel-vba vba

我编写了一个UDF,它从工作表中返回范围的地址(没有标题的列)。输出是一个字符串,如" $ A $ 2 $ A $ 5"。在另一个工作表中,我想在相应的单元格A2到A5上应用几个工作表函数,例如MAX。 当使用相应的字符串值替换UDF时,MAX和UDF的组合会导致错误消息(#Value):MAX($ A $ 2 $ A $ 5)有效。 有没有办法让这项工作?代码:

Public Function SELECTH(SheetName As String, HeaderName As String) As String

   Dim ColIndex As Integer
   Dim MaxRowIndex As Integer

   ColIndex = ActiveWorkbook.Worksheets(SheetName).Rows(1).Find(HeaderName).Column
   MaxRowIndex = ActiveWorkbook.Worksheets(SheetName).Cells(1, 1).End(xlDown).Row

   SELECTH = ActiveWorkbook.Worksheets(SheetName).Range(Cells(2, ColIndex), Cells(MaxRowIndex, ColIndex)).Address()

End Function

1 个答案:

答案 0 :(得分:2)

返回范围而不是字符串:

Public Function SELECTH(SheetName As String, HeaderName As String) As Range

Dim ColIndex As Long
Dim MaxRowIndex As Long
    With ActiveWorkbook.Worksheets(SheetName)
        ColIndex = .Rows(1).Find(HeaderName).Column
        MaxRowIndex = .Cells(1, 1).End(xlDown).Row

        Set SELECTH = .Range(.Cells(2, ColIndex), .Cells(MaxRowIndex, ColIndex))
    End With

End Function