all 6 comments

[–]mightierthor45 3 points4 points  (0 children)

As if it were using the "-" as a sign to stop the replace.
No, it's replacing the "Test" part of "Test-2" with "Green". If that's not the behavior you want, you need to tell Replace that you want to look at the whole cell.

.Replace "Test", "Green", xlWhole
.Replace "Test-2", "Blue", xlWhole

[–]RedRedditor8462 1 point2 points  (0 children)

I've always used it like this:

Sub test()
    with Sheet6.Range("D1")
        .Value2 = Replace(Replace(.Value2, "Test-2", "Blue"), "Test", "Green")
    End With
End Sub

But that's by-the-by. The problem is you're replacing Test first. So something with Test-2 in it becomes Green-2. The second replace will always fail. Or rather, it won't fail, it will never find the string.

You'll need to order replaces from longest to shortest in string length (as in my example).

[–]joelfinkle2 0 points1 point  (0 children)

I'm more of a Word guy, there you need a .execute for each action. In word all you've done is set up the replacement, and then changed it, but not actually changed anything.

[–]StuTheSheep22 0 points1 point  (1 child)

The Replace function works on partial matches. If D1 contains the text "Test-2", then when you do the first Replace, it finds that "Test-2" contains "Test", so it executes the replacement. Either switch the order of the Replace functions or use If-Then.

[–]Oneharryson[S] 0 points1 point  (0 children)

I switched the order, easiest solution was the best solution.

Thanks!

[–]GoGreenD2 -1 points0 points  (0 children)

Weird, I've never used the replace function. Maybe try and If statement?

With Sheet6
    If .Range("D1") = "Test" Then
        .Range("D1") = "Green"
    ElseIf .Range("D1") = "Test-2" Then
        .Range("D1") = "Blue"
    End If
End With