在ComboBox中显示具有不同值的文本

时间:2015-04-16 15:40:41

标签: excel-vba vba excel

有没有办法在组合框列表中显示项目但是给它一个不同的值?

说我有" 1-03"在我的列表中代表1' 3"但我想要" 1.25"分配给它,所以我的公式将正确计算。

Private Sub UserForm_Activate()

'Values for cmbxSpans
cmbxSpans.AddItem "1-03"

End Sub

1 个答案:

答案 0 :(得分:0)

没有。 Excel不提供项目(List(i)中的条目)的其他属性,以区分显示值和“实际”值。 ListBox中的项目存储为Strings。如果您想要双重表示(即1-03 = 1.25),则必须在添加/读取项目时处理转换。

以下是基于1-03示例的一组此类转化。

Private Sub CommandButton1_Click()

    ListBox1.AddItem "1-03"

    'read item
    Dim height As Double
    height = FormatToNumber(ListBox1.List(0))

    'do some math
    height = height * 2

    'add it back it
    ListBox1.AddItem NumberToFormat(height)

End Sub

Function FormatToNumber(str_feet_inch As String) As Double
    Dim values As Variant

    'split based on -
    values = Split(str_feet_inch, "-")

    'do the math, using 12# to ensure double result
    FormatToNumber = values(0) + values(1) / 12#
End Function

Function NumberToFormat(val As Double) As String

    Dim str_feet As String
    Dim str_inch As String

    str_feet = Format(Int(val), "0")
    str_inch = Format((val - Int(val)) * 12, "00")

    NumberToFormat = str_feet & "-" & str_inch


End Function