Prakash Singh
Prakash Singh

Reputation: 9

comparing the content of two cells in VBA

I need to compare the content of two cells in macro

RC1=2.0
RC2=2

I am using if(RC1=RC2,"''","x") for this which prints x for the above input but 2.0 and 2 are same, I need it to be '' in this case, please suggest

Upvotes: 1

Views: 4025

Answers (2)

CLR
CLR

Reputation: 12279

Your failing 'code' suggests you're merely using a formula:

if(RC1=RC2,"''","x")

If you are happy using a formula to test them, you could use:

IF(VALUE(RC1)=VALUE(RC2),"''","x")

Be aware though, a blank cell has a VALUE of 0 (zero) so an empty cell would match a cell containing 0.00

Upvotes: 1

Pierre Chevallier
Pierre Chevallier

Reputation: 754

First and foremost

You are trying to compare two different data types, let's say consider that one is an integer, which does not have decimal values, and the other one a double, with a decimal.

I would suggest you to have a better look at data types in VBA.

Hence we will need to convert the types to one that is the same for both cells with CDbl() to convert them to double. To put it simply, since integers are a simpler form of doubles we will use the more complete type of both.

Code to compare the types

Sub COMPARING_TYPES()

Dim a As Double, b As Double

' Let's assume the both values are numeric
a = CDbl(Cells(1, 1))
b = CDbl(Cells(2, 1))

If a = b Then
    ' Other code to execute when the values are matching
End If

End Sub

This is all considering you want to compare the numbers in a VBA code.

Upvotes: 0

Related Questions