且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Excel中具有多个条件的条件格式设置(自定义格式)

更新时间:2022-06-13 02:13:11

本文(第三个示例)提到格式语句中仅允许两个条件:

This article (third example) mentions that only two conditions in the formatting statement are allowed:

自定义数字格式最多可以指定两个条件.这是因为自定义数字格式只允许使用四个部分,而保留两个部分.第四部分始终指定文本格式,而另一部分则需要详细说明其他所有内容"(数字方式)的格式.

Custom number formats allow up to two conditions to be specified. This is because only four sections are allowed for custom number formatting and two are reserved. The fourth section always specifies text formatting and one other section is required to detail how ‘everything else’ (numerically) will be formatted.

并且如Excel 2010帮助中所述:

And as mentioned in the Excel 2010 help:

数字格式最多可以包含四部分代码,用分号分隔.这些代码部分按此顺序定义了正数,负数,零值和文本的格式.

A number format can have up to four sections of code, separated by semicolons. These code sections define the format for positive numbers, negative numbers, zero values, and text, in that order.

<POSITIVE>;<NEGATIVE>;<ZERO>;<TEXT>

作为中间解决方案,您可以使用我编写的以下VBA函数:

As an intermediate solution you could use the following VBA function I have written:

Function FormatNumber(val As Variant) As String
If IsNumeric(val) Then
    Dim NumVal As String
    NumVal = ""

    If val > 1000000000 Then
        NumVal = Str(val / 1000000000#) & "B"
    ElseIf val > 1000000# Then
        NumVal = Str(val / 1000000#) & "M"
    ElseIf val > 1000# Then
        NumVal = Str(val / 1000#) & "K"
    Else
        NumVal = Str(val)
    End If

    FormatNumber = NumVal
Else
    FormatNumber = val
End If
End Function

这将导致:

第一列是原始编号,第二列是您建议的编号格式,第三列是VBA功能FormatNumber.请注意,FormatNumber的结果是字符串,因此您不能使用它们来计算.

First column is the original number, 2nd with the number formatting you proposed, and third with the VBA function FormatNumber. Note that the results of FormatNumber are Strings, so you cannot use them to calculate.