比较工作表值(文本和算术)

时间:2018-09-21 08:28:48

标签: excel-vba

我有一本具有2个工作表的excel工作簿,每个工作表由60行和7列组成(第一列由文本组成,其余仅由数字组成)。

我找到了VBA代码以比较两张纸的值。如果存在差异,则该单元格将填充为红色,但是包含数字的列存在问题:

Cell in 1st Sheet Value: 6102.75

Cell in 1st Sheet Value: 6102.75000001

->单元格突出显示为红色。

如果数字等于4个整数点,我应该对代码进行哪些更改以便不突出显示单元格?我认为我必须对代码进行更改,以便分别比较文本和数字。

Sub compareSheets(shtBefore As String, shtAfter As String)
Dim mycell As Range
Dim mydiffs As Integer

For Each mycell In ActiveWorkbook.Worksheets(shtAfter).UsedRange

If Not mycell.Value = ActiveWorkbook.Worksheets(shtBefore).Cells(mycell.Row, mycell.Column).Value Then

mycell.Interior.Color = vbRed

mydiffs = mydiffs + 1

Next

'Display a message box stating the number of differences found

MsgBox mydiffs & " differences found", vbInformation

ActiveWorkbook.Sheets(shtAfter).Select

End Sub

期待您的评论

2 个答案:

答案 0 :(得分:1)

使用IsNumeric确定两个值是否为数字,然后四舍五入将小数位截断为4位。

Sub compareSheets(shtBefore As String, shtAfter As String)

    Dim mycell As Range
    Dim mydiffs As Integer

    For Each mycell In ActiveWorkbook.Worksheets(shtAfter).UsedRange
        if isnumeric(mycell.Value) and isnumeric(ActiveWorkbook.Worksheets(shtBefore).Cells(mycell.Row, mycell.Column).Value) then

            If round(mycell.Value, 4) <> round(ActiveWorkbook.Worksheets(shtBefore).Cells(mycell.Row, mycell.Column).Value, 4) Then

                mycell.Interior.Color = vbRed
                mydiffs = mydiffs + 1

            end if

        elseif mycell.Value <> ActiveWorkbook.Worksheets(shtBefore).Cells(mycell.Row, mycell.Column).Value then

            mycell.Interior.Color = vbRed
            mydiffs = mydiffs + 1

        end if

    Next mycell 

    'Display a message box stating the number of differences found

    MsgBox mydiffs & " differences found", vbInformation

    ActiveWorkbook.Sheets(shtAfter).Select

End Sub

答案 1 :(得分:0)

您可以使用Format函数定义要比较的小数位数,并使用IsNumeric函数检查值是否为数字。

示例代码:

Cell A1: 6102.75    
Cell A2: 6102.75000001

Sub test
  'Since in your example both worksheets share the same layout, you only need to check
  'if one of the values is numeric, since the other value will automaticly be the same
  If IsNumeric(Cells(1,1).Value) Then
    MsgBox (Format(Cells(1,1).Value, "0.0000") = Format(Cells(1,1).Value, "0.0000"))
  Else
    MsgBox Cells(1,1).Value = Cells(1,2).Value
  End If      
End Sub
  

Format的第一个参数是您要格式化的值

     

Format的第二个参数是定义格式的字符串

     

点后的4个零定义小数位数


编辑: 由于@jeeped postet是使用Round函数的解决方案。

请注意,使用Format函数会舍去其余的小数位数,而不是四舍五入。

因此6102,756102,75005仍然相等。


EDIT2:

@jeeped改进了格式字符串,因此甚至不需要检查值是数字还是文本。

更新的示例代码:

Cell A1: 6102.75    
Cell A2: 6102.75000001

Sub test
  MsgBox Format(Cells(1, 1).Value, "0.0000;@") = Format(Cells(1, 2).Value, "0.0000;@")
End Sub

使用此Format-String,该函数将返回切成4个十进制数字的数字(如果是数字),或者返回整个文本(如果是文本)。