how to test if multiple cells equal respective values in vba?

joshman108

Active Member
Joined
Jul 6, 2016
Messages
310
I would like to set up a logic that says something like:

Check to see if cells A1:W1 are equal to these strings in succession: ("string1", "string2", "string3"), where string1 corresponds to A1, string2 corresponds to B1, string3 corresponds to C1 and etc. If any of the cells to not equal their corresponding string value then abort and throw a message box saying something like "re order columns".

It would be nice if the message box said specifically which cell did not match it's correspond string value, for instance: "A1 does not say 'string1' ", but if that's not possible then that's fine. A general error will work.

I can of course do many different if statements checking the cells one by one but I would like a more elegant and easier solution.

Thanks!
 

Excel Facts

Can Excel fill bagel flavors?
You can teach Excel a new custom list. Type the list in cells, File, Options, Advanced, Edit Custom Lists, Import, OK
This might work for you

Code:
Sub CheckColumns()
Dim myarray As Variant, i As Long
myarray = Array("string1", "string2", "string3") ' add all extra 20 strings


For i = 1 To 3 ' change to 23 when you've populated all your array




If Cells(1, i).Value <> myarray(i - 1) Then MsgBox "Re-order columns, mismatch in column " & Replace(Cells(1, i).Address(True, False), "$1", ""): Exit Sub
Next i


End Sub
 
Last edited:
Upvote 0

Forum statistics

Threads
1,223,246
Messages
6,170,996
Members
452,373
Latest member
TimReeks

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top