1

I am trying to pull zipcodes from a Microsoft SQL Database and everything works good with US Zipcodes, but once I start to use Canadian Zip Codes, I get the following message:

conversion failed when converting the varchar value 'L0S1J0' to data type int.

I know that L0S1J0 is not a integer, but what I don't understand is why Excel VBA wants to pull the data as an integer. I tried to search for pulling data in ways other than int, but I am not having any luck with the right keywords. I have tried things like Cast and Convert, but I cant get anything to work, other than removing the Canadian Zip Codes out of the database.

Here is my query that I am currently running and the Zip Codes are stored under the LookupID field.

Select Distance1, Distance2, LookupID FROM excel.dbo.miles WHERE LookupID =" & Worksheets("sheet1").Range("C2").Value

Any help in this is greatly appreciated!

4
  • What does the rest of your VBA look like? Commented Dec 17, 2015 at 16:21
  • This still gave me the error message. Thanks for your assistance however :-) Commented Dec 17, 2015 at 18:01
  • I had noticed the missing quote marks but I expected you to see a different error though. Glad you got it fixed. Commented Dec 17, 2015 at 18:03
  • Just for reference when I try a similar query I get: Invalid column name 'L0S1J0'. Who knows. Commented Dec 17, 2015 at 18:40

1 Answer 1

4

Your problem is in your where clause. Change to:

WHERE LookupID ='" & Worksheets("sheet1").Range("C2").Value & "'"

You need to put single quotes around string literals.

You should consider doing a parameterized query to protect from SQL Injection issues. For example with ADO use the CreateParameter method.

Sign up to request clarification or add additional context in comments.

1 Comment

Pefect! Thank you for your time. Works like a charm now :-D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.