• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Error in match through VBA

kaushik03

Member
Hi all,

I am getting an error while doing match for date.

In the workbook attached, I am trying to find the date stored in I2 in the range A1 to Z1, but getting an error.(see the code in mod1).

Could you plz fix it and let me know the reason!

Kaushik
 

Attachments

  • Match.xlsm
    16.3 KB · Views: 2
Hi Kaushik ,

Try this code :

Code:
Sub Test()
    Dim X As Long
    X = Sheets("Sheet1").Range("I10").Value

    y = Application.WorksheetFunction.Match(X, Sheets("Sheet1").Range("A1:Z1"), 0)
End Sub

As an alternative , you can also use a conversion function as follows :

Code:
Sub Test()
    X = Sheets("Sheet1").Range("I10").Value

    y = Application.WorksheetFunction.Match(CLng(X), Sheets("Sheet1").Range("A1:Z1"), 0)
End Sub

The problem is that if you do not explicitly declare the type of a variable , by default it is a Variant ; in this case , as a consequence of the assignment in the following statement :

X = Sheets("Sheet1").Range("I10").Value

X becomes a variable of Date type ; consequently , in the MATCH statement , the VBA Date type variable cannot match with the dates in the range A1:Z1 ( in which the values are just numbers ; remember that in Excel dates are actually numbers ).

Declaring the variable X as of type Long enables the MATCH to work , since the types of X and the dates in A1:Z1 now are identical.

Similarly , the forced conversion using the CLng function converts the Date type variable to one of Long type.

Narayan
 
Last edited:
It worked...thanks Narayan.....you are brilliant...

But just curious...earlier I did the same without declaring the variable type and it worked...could you please explain me the logic behind!

Regards,
Kaushik
 
Back
Top