【问题标题】:Format a Multiple Range Listbox with Currency Format使用货币格式格式化多范围列表框
【发布时间】:2019-06-17 23:12:45
【问题描述】:

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

这是一些测试数据:

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

这是我现在得到的结果:

【问题讨论】:

  • Format 仅适用于数值,不适用于 Strings。您无法格式化字符串,您需要将它们切成小块以获得可以格式化的数值。
  • 认为您的问题是 .List(.ListCount - 1, 2) 没有引用 second 列表框列,而是引用可能的 third 列,作为列表索引是零界限,并且您不能将添加的列表行格式化为一个整体(默认情况下使用 AddItem 包含 10 列),您只能将单个格式化字符串分配给每个列表列:-)
  • 谢谢你们!我让它工作了!
  • @Andrew,不,您必须将从 List(.Listcount - 1, 0) 开始的每个元素格式化为第一个元素,List(.Listcount - 1, 2) 作为第二个元素。 .List(.ListCount - 1, 3) 甚至会引用第四列。 - 见 Peh 的回答。 :-)
  • @Andrew 请注意,您应该在LR1 = Range("A" & Rows.Count) 中指定工作表,例如LR1 = ws1.Range("A" & ws1.Rows.Count),否则它可能会选择错误的工作表。

标签: excel vba listbox format userform


【解决方案1】:

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

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) 是您的第二列(不是第一列)。

【讨论】:

  • @PEH - 作为旁注:.AddItem 甚至默认添加 10 个空列元素(而使用例如整个数据集的数组分配方法不是仅限于该固定数量限制)。
  • @T.M.是,对的!我将把“添加第一列”改成“填充第一列”。
  • @Andrew FYI :-) 关于上述数组方法的可能进一步阅读:Populate Listbox with multiple columns
猜你喜欢
  • 2018-01-07
  • 2013-10-18
  • 2011-09-16
  • 1970-01-01
  • 1970-01-01
  • 2016-04-25
  • 2012-05-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多