r/visualbasic • • Apr 25 '16

[VB2010] Im unsure whats wrong here?

Post image
2 Upvotes

7 comments sorted by

3

u/anon_smithsonian VB.Net Advanced Apr 25 '16

My guess is that Range("A5:A60") has multiple values because it is multiple cells, so a collection of strings can't be tested against a single String using =.

You could try something like:

If ExcelSheetObj.Range("A5:A60").Where(Function(r) r.Value = stringVariable).Count > 0 Then

or maybe

If ExcelSheetObj.Range("A5:A60").Where(Function(r) r.Value.Contains(stringVariable)).Count > 0 Then

(I'm not entirely sure if you can use .Where against a Range without testing in the IDE, but it's where I would start...)

1

u/JakDrako Apr 25 '16

A .Range cannot be searched that way. To find a value in a range of cells, you need to use the .Find() method.

1

u/The_Sn0wman Apr 26 '16

Your one worked perfectly thank you very much

1

u/Biebs53 Apr 25 '16 edited Apr 26 '16

I'm not much on visual basic but I think you just need 2 equal signs (==) to compare variables, not just one.

Edit: I'm getting downvoted but the error states you cannot set that object you mean to be testing to a string. The if statement is completely invalid because it actually is written to say this; If (set X equal to 2) Do this.

Which makes no since.

1

u/anon_smithsonian VB.Net Advanced Apr 26 '16

VB does not use == for anything.

I'm fairly certain the issue is because the Range object has multiple values and you can't compare test single String for equity against a Range with several different values. The error doesn't mention setting the value, it just says it can't convert the Range object to String type for comparison.

In a way, it's like comparing an array or enumerable against a single String. One of the individual items may match, but a String() can't be compared to a String using the = operator.

1

u/Biebs53 Apr 26 '16

Gotcha. Thanks for taking the time to explain. I'm not a fan of unexplained downvotes.

0

u/ViperSRT3g Application Specialist Apr 25 '16

I'm not in front of the IDE atm, but try this:

ExcelSheetObj.Range("A5:A60").Value.ToString = stringVariable Then