In an Excel 2007 VB Macro, I’m trying to do is take a comma separate String, split it, and then reduce it, removing duplicate consecutive values. So “2,2,2,1,1” would become “2,1”, or “3,3,3,2,3,3,3” would become “3,2,3”.
It looks like it should work, but when it gets to the “If currentVal.equals(prevVal) = False Then”, it his a runtime error 424, ‘Object required’.
It’s been forever since I did any VB, and that was VP6.
Sheets("Sheet1").Select
Range("I1").Select
Dim data() As String
Dim currentVal, prevVal As String
Dim output As String
Dim temp As Boolean
Do Until Selection.Value = ""
data = Split(Selection, ",")
output = ""
prevVal = ""
For Each elem In data
currentVal = CStr(elem)
If currentVal.equals(prevVal) = False Then
output = output + elem + ","
End If
Next elem
Selection.Value = output
Selection.Offset(1, 0).Select
Loop
There’s a few problems. First, you can’t use:
You must use:
or:
…as you can’t shortcut types in VBA unfortunately. Secondly, strings aren’t objects in VBA so there’s no .equals (or any other method). You want:
Lastly, you need to set prevVal at the end of your loop or your code won’t work as expected.
EDIT Here’s some working code: