简体   繁体   English

如何在Excel UDF中使用常量值?

[英]How to use constant values in Excel UDF?

I've been struggling to come up with a UDF in Excel. 我一直在努力在Excel中提出UDF。 basically what I'm looking for is a function that would take 2 input parameters(constant) provided by a user, then the function would return one of the values pre-stored in an excel table somewhere. 基本上我正在寻找的是一个函数,它将接受用户提供的2个输入参数(常量),然后该函数将返回预先存储在excel表中某个位置的值之一。 Here's what it would look like: 如下所示:

month Peak off 高峰期关闭

  1. January 320 176 一月320176
  2. February 320 128 二月320128
  3. March 368 252 3月368252
  4. April 352 128 352 128年4月
  5. May 305 320 305320年5月

The function would be like this: =Hours(February, Peak) then it would return February peak hours and so on. 该函数将是这样的:= Hours(February,Peak)然后它将返回2月的高峰时间,依此类推。

I appreciate all the help. 我感谢所有的帮助。 Thanks a lot 非常感谢

EDIT: Code added as comment 编辑:代码添加为注释

Public Function calculateHours(ByVal mo As Variant, ByVal period As Variant) As Integer    
 Dim tablette As Range 
 Set tablette = Worksheets("Hours").Range("U4:V15") 
 Set valueRange = Worksheets("Hours").Range("U4:U15") 
 period = "peak" 
 For Each ref In valueRange 
   mo = WorksheetFunction.VLookup(ref, tablette, 1, 0) 
 Next 
 ref calculateHours = WorksheetFunction.VLookup(mo, tablette, 2, False) 
End Function

When I try to use this function such in =calculateHours(january, peak) I only get the last value from table regardless what the parameters are 当我尝试在= calculateHours(january,peak)中使用此函数时,无论参数是什么,我都只能从表中获取最后一个值

Consider: 考虑:

Public Function ReturnVale(period As String, MinMax As String) As Variant
    months = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
    Off = Array(330, 347, 366, 393, 307, 353, 310, 347, 332, 307, 400, 333)
    Peak = Array(399, 428, 440, 446, 366, 431, 370, 413, 389, 364, 470, 421)
    For i = LBound(months) To UBound(months)
        If period = months(i) Then
            GoTo done
        End If
    Next i
    ReturnVale = "NOT FOUND"
    Exit Function
done:
    If MinMax = "Peak" Then
        ReturnVale = Peak(i)
    Else
        ReturnVale = Off(i)
    End If
End Function

Naturally you would modify the Array() statements to match your requirements. 自然地,您将修改Array()语句以符合您的要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM