我想要一个显示自定义格式的 Excel 工作表。自定义格式使用另一个单元格的内容。这是一个例子:
Column A : Show a column of numbers in accounting format in the currency of cell(b1).
Cell(B1) : "XYZ"
目的是用户可以输入自己的货币。我知道在 Excel 中有格式化工具可以做到这一点,但这是一个基于另一个单元格内容实现自定义格式的问题。这才是真正的问题...
工作表的私有代码表中的 worksheet_change 可以更改 A 列中的数字格式。
private sub worksheet_change (byval target as range)
if not intersect(target, range("b1")) is nothing then
if len(cells(1, "b").value2) = 3 then
dim f as string
f = ucase(cells(1, "b").value2)
f = "0 \" & left(f, 1) & "\" & mid(f, 2, 1) & "\" & right(f, 1)
range(cells(2, "a"), cells(rows.count, "a").end(xlup)).numberformat = f
end if
end if
end sub
在不删除之前创建的 cnfs 的情况下,可以在现有的数字格式中添加最大数量的自定义数字格式;我觉得大概30左右吧。
假设你想要这样的东西:
..然后把它放在工作表模块中:
Sub worksheet_Change(ByVal Target As Range)
Dim sFormat As String
If Not Intersect(Target, Range("NumberFormat")) Is Nothing Then
sFormat = Chr(34) & Target.Value & Chr(34) & " "
Range("FormatWhat").NumberFormat = sFormat & "$#,##0;" & sFormat & "[Red]-$#,##0;-"
End If
End Sub
...并在名称框中为 B1 提供名称 NumberFormat:
...并同样将 A 列的部分或全部命名为“FormatWhat”。
(使用命名范围可避免在代码中硬编码引用。如果将单元格地址硬编码到代码中,如果您(或用户)稍后在上方/左侧添加新行/列,这些引用将指向错误的位置那些硬编码的引用。使用名称可以避免这种情况,并使代码更健壮。
我几乎从不在代码中硬编码单元格地址。我几乎总是使用 Excel 表格(即 ListObjects)来保存 VBA 与之交互的任何数据,出于同样的原因……ListObjects 是 Excel 自动扩展/收缩以适应数据的动态命名范围。)