10

I want to replace words in a column with another word, however my code does not seem to be working, I'm still trying to get a grip on the coding language, but it's just not intuitive to me.

Situation:

Global Macro - Equities
Global Macro - Bonds
Global Macro - FX
.
.
.
And so on...

Desired outcome:

GM - Equities
GM - Bonds
GM - FX
.
.
.

My code

Sub ReplaceFundNames()

    Dim FundName As String
    Dim CorrectedName As String
    Dim ws As Worksheet
    Dim LastRow As Long

    Set ws = ActiveSheet
    LastRow = Range("B" & Rows.Count).End(xlDown).Row

    FundName = Range(LastRow)
    CorrectedName = Replace(FundName, "Global Macro", "GM")

    Range("B" & LastRow).Value = CorrectedName


End Sub

Thank you!

1
  • Your code is performing a replacement on cell B1048576 in the active sheet, and only if that cell contains "Global Macro" Commented Jun 1, 2017 at 3:15

1 Answer 1

14

The Replace function in VBA is designed to work on a single string, whereas the Range.Replace method is designed to work on a Range.

As such, you can perform your replacements in a single statement:

ActiveSheet.Range("B:B").Replace "Global Macro", "GM"

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

5 Comments

Do you mean to replace the entire code above with this single statement?
Yes. You could narrow it down to the number of used rows, but assuming there isn't any data below or above the range you need values replaced in, the line above should suffice. The important thing is that you use the Range.Replace method rather than the VBA.Replace function.
ah ok, thanks for the tip. However, I've tried the code and this error message pops up: "Compile error: Expected function or variable"
If you use the line between a Sub ReplaceFundNames() line, and an End Sub line, I can't see any way that you can get a compile error. Are you certain you haven't made a typo, and/or that you don't have an error elsewhere in your code? ActiveSheet.Range("B:B").Replace "Global Macro", "GM" will work, unless you don't have an active sheet.
ok, I tried it on a new spreadsheet, works like a charm, thanks so much!

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.