I am using a listbox in an userform which displays a unique values from a column which is formatted as percentage. I am generating a unique list/values by using dictionary object and feeding it to a listbox.
My problem is all the values are shown as decimal numbers in listbox not as percentages. Any idea how to show them as percentages/format?.
FYI: listbox values can change depends on the user selection text/numbers/date/currency/percentage
unique list code
Sub UniqData(fString As String, cbNr As Integer) ' fString as string
Dim d As Object
With Sheets("xxx")
cNr = WorksheetFunction.Match(fString, .Rows(1), 0)
lRo = .Cells(Rows.Count, 1).End(xlUp).Row
arrD = .Range(.Cells(2, cNr), .Cells(lRo, cNr))
Set d = CreateObject("scripting.dictionary")
For Each c In arrD
If Len(c) > 0 Then
d00 = dic.Item(c.Text)
End If
Next c
k = d.keys
End With
UserForm1.Controls("lb" & cbNr).List = k
End Sub
like this.
Formatting cells using the spreadsheet only modifies how the number is going to visually present to a user. The underlying value remains unchanged.
Therefore, you need to explicitly format the value to what you want it to look like as you are adding it the dictionary.
d.Add Format(c, "0.0%"), c
Answer:
As mentionned by @Meehow, the use c.Text
may generate error if the data is too larged to be displayed in the cell!
So, use Format(c.Value, "0.0%")
as key in the d.Add
line and you’ll have the formatting from the Excel cell :
Sub UniqData(fString As String, cbNr As Integer) ‘ fString as string
Dim d As Object
With Sheets("xxx")
cNr = WorksheetFunction.Match(fString, .Rows(1), 0)
lRo = .Cells(Rows.Count, 1).End(xlUp).Row
arrD = .Range(.Cells(2, cNr), .Cells(lRo, cNr))
Set d = CreateObject("scripting.dictionary")
For Each c in arrD
d.Add Format(c.Value, c.NumberFormat), c.Value
Next c
k = d.keys
End With
UserForm1.Controls("lb" & cbNr).List = k
End Sub
Tags: excelexcel, list