简体   繁体   English

使用VBA比较Excel中两个单元格的数字格式

[英]Compare number formatting of two cells in excel using vba

My problem: 我的问题:

Cell A1: value =12 and the number property is general. 单元格A1:值= 12,数字属性为常规。 Cell A2: value =12 and the number property is number with 2 decimal points, so the number is shown as "12.00" 单元格A2:值= 12,并且number属性是带有2个小数点的数字,因此该数字显示为“ 12.00”

How can I validate if both cells have the same number property, either in VBA using macros or in any other way? 如何在VBA使用宏或以其他任何方式验证两个单元格是否具有相同的number属性?

You can compare their NumberFormat property: 您可以比较它们的NumberFormat属性:

If Range("A1").NumberFormat = Range("A2").NumberFormat Then

However, There are a number of different formats, including custom formats, that can be applied to cells that would make them look the same, without them having exactly the same NumberFormat value. 但是,可以将许多不同的格式(包括自定义格式)应用于单元格,以使它们看起来相同,而不必具有完全相同的NumberFormat值。

This means that comparing formats will never be as reliable as comparing the values. 这意味着比较格式永远不会像比较值那样可靠。 (It is also unusual to need to compare formats.) (需要比较格式也很不寻常。)

You can use the NumberFormat method. 您可以使用NumberFormat方法。

Using this code, with 12 in A1 (formatted as general) and 12 in B1 (formatted as 12.00) 使用此代码,A1中的12 (常规格式)和B1中的12 (格式12.00)

Option Explicit
Sub Stuff()

    MsgBox Range("A1").NumberFormat
    MsgBox Range("B1").NumberFormat

End Sub

Will return messages of "General" and "0.00" respectively. 将分别返回消息“常规”和“ 0.00”。

So using 所以用

If Range("A1").NumberFormat = Range("B1").NumberFormat Then
    -- do stuff here
End If

Will tell you if they are equal to one another or not. 会告诉您它们是否相等。

It sounds like you are really concerned with the values of the cells. 听起来您真的很关心单元格的 The .NumberFormat property simply masks how the value appears, visually, to the user of the spreadsheet. .NumberFormat属性只是掩盖了该在视觉上对电子表格用户的显示方式。

So you can easily do an equivalence test on the two values , like: 因此,您可以轻松地对两个进行等效测试,例如:

Sub Test()

MsgBox [A1].Value = [A2].Value

End Sub

Or you could do this in the worksheet formula: 或者,您可以在工作表公式中执行此操作:

=A1=A2

That formula should return either True or False , and should ignore the cell's formatting . 该公式应返回TrueFalse ,并应忽略单元格的formatting

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM