Lelio Faieta
Lelio Faieta

Reputation: 6686

compare two variable with same value returns false

In an Excel macro I have the following statement:

mese= 6 'from excel cell
mese_tgt = 6 'from input box
quindicina =1 'from excel cell
quindicina_tgt = 1 'from input box

If mese = mese_tgt And quindicina = quindicina_tgt Then
'do stuff here
End If

This will always return false. If I debug i see that the values are correctly assigned so that I have

If 6 = 6 And 1 = 1 Then

What am I missing? For what I know vba doesn't require == for comparison but maybe I am wrong?

EDIT: I do not declare the variables but just do:

mese_tgt = InputBox("Che mese vuoi elaborare?", "Scegli il mese")
quindicina_tgt = InputBox("Quale quindicina vuoi elaborare? 1 o 2", "Scegli la quindicina")
mese = sh2.Range("B" & riga).Value
quindicina = sh2.Range("C" & riga).Value

Upvotes: 0

Views: 1037

Answers (1)

Scott Craner
Scott Craner

Reputation: 152525

The problem is that:

mese_tgt = InputBox("Che mese vuoi elaborare?", "Scegli il mese")

is returning a string and not a number. In Excel "1" <> 1 So you must declare your variable so VBA does not guess to the type:

Dim mese as Long, mese_tgt as Long, quindicina as Long, quindicina_tgt as Long

Now VBA will not guess the type and it will force the result as a Long.

One Note Long are integers only, no decimals. If your numbers have decimals then use Double instead of Long

One should get in the habit of always declaring their variables.

Upvotes: 3

Related Questions