更改组合框格式后如何修复组合框的“无效属性值”

时间:2019-05-09 14:36:19

标签: excel vba combobox userform

更改combobox5格式后,现在给出“无效的属性值。

    `Option Explicit
Private Sub ComboBox5_Change()
ComboBox5 = Format(ComboBox5, "00%")
End Sub
' CODE MIMIC "DATA VALIDATION"
Private Sub UserForm_Initialize()

    Me.ComboBox1.List = Worksheets("B16.5 & B16.47 SERIES A").Range("R15:R16").Value
    Me.ComboBox2.List = Worksheets("B16.5 & B16.47 SERIES A").Range("U5:U9").Value
    Me.ComboBox3.List = Worksheets("B16.5 & B16.47 SERIES A").Range("B5:B40").Value
    Me.ComboBox4.List = Worksheets("B16.5 & B16.47 SERIES A").Range("R5:R12").Value
    Me.ComboBox5.List = Worksheets("B16.5 & B16.47 SERIES A").Range("T5:T10").Value
    Me.ComboBox6.List = Worksheets("B16.5 & B16.47 SERIES A").Range("R18:R19").Value


End Sub
`

1 个答案:

答案 0 :(得分:1)

组合框值只能是列表中的值。请注意,获取单元格的.Value属性将获取其基础值(例如.57),而不是其格式化的显示值(例如57%),这很可能就是您遇到此问题的原因。不幸的是,您需要将这些值加载到数组中,然后将这些值格式化为所需的显示文本,然后将其加载到组合框列表中。我可以想到的是,实际上并没有一个单一的解决方案,但是类似的东西应该可以工作(然后不需要更改事件):

Private Sub UserForm_Initialize()

    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("B16.5 & B16.47 SERIES A")

    Dim aLists(1 To 6, 1 To 2) As Variant
    'This is the combobox               'This is the range where the combobox gets its values
    Set aLists(1, 1) = Me.ComboBox1:    Set aLists(1, 2) = ws.Range("R15:R16")
    Set aLists(2, 1) = Me.ComboBox2:    Set aLists(2, 2) = ws.Range("U5:U9")
    Set aLists(3, 1) = Me.ComboBox3:    Set aLists(3, 2) = ws.Range("B5:B40")
    Set aLists(4, 1) = Me.ComboBox4:    Set aLists(4, 2) = ws.Range("R5:R12")
    Set aLists(5, 1) = Me.ComboBox5:    Set aLists(5, 2) = ws.Range("T5:T10")
    Set aLists(6, 1) = Me.ComboBox6:    Set aLists(6, 2) = ws.Range("R18:R19")

    'Loop through your list of comboboxes and load values
    Dim aTemp As Variant
    Dim i As Long, j As Long
    For i = LBound(aLists, 1) To UBound(aLists, 1)
        Select Case aLists(i, 1).Name
            'Specify the comboboxes that should have the percent format here
            Case "ComboBox5"
                aTemp = aLists(i, 2).Value
                For j = LBound(aTemp, 1) To UBound(aTemp, 1)
                    aTemp(j, 1) = Format(aTemp(j, 1), "00%")
                Next j
                aLists(i, 1).List = aTemp

            'Can use this same method to apply different formats as well to different comboboxes, add additional conditions here

            'Otherwise just load the values as is
            Case Else
                aLists(i, 1).List = aLists(i, 2).Value

        End Select
    Next i

End Sub

结果截图:

enter image description here