使用货币格式格式化多范围列表框

时间:2019-06-17 13:31:38

标签: excel vba listbox format userform

我正在尝试使用货币格式(“ $#,## 0.00”)格式化列表框的第二列,但遇到了麻烦。任何帮助将不胜感激!

以下是一些测试数据:

Data

Dim ws1 As Worksheet
Set ws1 = ThisWorkbook.Sheets("PivotTable")

Dim rng1 As Range
Dim LR1 As Long
LR1 = Range("A" & Rows.Count).End(xlUp).Row
Set rng1 = ws1.Range("A1:A" & LR1).SpecialCells(xlCellTypeVisible)

With Me.ListBox1
    .ColumnCount = 2
    .ColumnWidths = "120,100"

    For Each Cell In rng1
        .AddItem Format(Cell.Value, "$#,##0.00")
        .List(.ListCount - 1, 1) = Cell.Offset(0, 1).Value
        .List(.ListCount - 1, 2) = Cell.Offset(0, 2).Value 'Format this column        
    Next Cell
End With

这是我现在得到的结果:

Error Result

1 个答案:

答案 0 :(得分:2)

我认为@TM是正确的。请尝试以下操作:

For Each Cell In rng1

    .AddItem Cell.Value 'this is your first column
    .List(.ListCount - 1, 1) = Format(Cell.Offset(0, 1).Value, "$#,##0.00") 'this is your second one
    'you tried to format the 3rd one (which was not visible because of .ColumnCount = 2:
    '.List(.ListCount - 1, 2) = Cell.Offset(0, 2).Value 'Format this column
Next Cell

说明:

.AddItem填充第一列。 .List(row, column)中的列计数以0开始,因此.AddItem填充了列0,这意味着.List(.ListCount - 1, 1)是您的第二列(而不是第一列)。