繁体   English   中英

如何在Excel UDF中使用枚举标识符

[英]How can I use enum identifiers in Excel UDF

我用以下代码创建了一个名为EnergyPrice的函数:

这是我正在寻找的价格

Prijstabel                  
                               fixed           variable 
Startdate   Einddate    gas       electra   gas      electra
                        €/a       €/a       ct/KWh   ct/KWh

1-1-2010    1-7-2010    181,00    235,00     0,11      0,33 
1-7-2010    1-1-2011    362,00    470,00     0,33      1,30 
1-1-2011    1-7-2011    191,00    245,00     0,22      0,65 
1-7-2011    1-1-2012    162,35    208,25     0,19      0,55 
1-1-2012    1-7-2012    324,70    416,50     0,37      1,11 

这是相关的代码

Public Enum Energietype
  v_gas = 1
  v_electricity = 2
End Enum

Public Enum FixedOrVariable
  v_fixed = 1
  v_variable = 2
End Enum

Public Function EnergyPrice(PriceDate As Date, E_type As Energietype, variabel As FixedOrVariable) As Variant

Dim PrijsTable As Range
Dim RowNr As Integer
Dim Found As Boolean
Dim KolomNr As Integer

  Set PrijsTable = Range("EnergyPriceTable")
  If PrijsTable.Columns.Count <> 6 Then Err.Raise Number:=vbObjectError + 1000, Description:="No valid valid pricetable defined"
  RowNr = 1
  Found = False

  While Not (Found) And (RowNr <= PriceTable.Rows.Count)
    Found = (PriceTable.Cells(RowNr, 1).Value <= PriceDate) And (PriceTable.Cells(RowNr, 2) > PriceDate)
    If Not (Found) Then RowNr = RowNr + 1
  Wend
  If Found Then
    If E_type = v_gas Then KolomNr = 1
    If E_type = v_elektra Then KolomNr = 2
    If variabel = v_variabel Then KolomNr = KolomNr * 2
    KolomNr = KolomNr + 2
    EnergyPrice = PriceTable.Cells(RowNr, KolomNr).Value
  Else
    EnergyPrice = Empty
  End If
End Function

问题是如何在Excel电子表格中使用上述枚举? 所以我可以输入如下公式:

在此输入图像描述

如果我使用数字1,2,函数工作正常,但我想使用枚举名称。
这可以仅使用Excel VBA完成吗?

如果将枚举作为定义的名称添加到工作簿,则可以将它们传递给函数,并且传递的值是您为枚举设置的实际值。 如果您愿意,可以手动或通过VBA执行此操作。

例:

ActiveWorkbook.Names.Add Name:="v_gas", RefersToR1C1:="=1"
ActiveWorkbook.Names.Add Name:="v_fixed", RefersToR1C1:="=2"

我看到的唯一方法是在工作簿中定义Names,为它们分配Enums的常量。

  • 从菜单中: Insert ... Name .... Define
  • 名称: v_gas
  • 指: =1

或者,您可以通过VBA创建这些名称,但这没有兴趣,因为它将是1镜头(名称随工作簿一起保存)。

通过使用这些名称,用户将能够在输入公式时使用F3。

暂无
暂无

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

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