VBA: Find and replace an "array" of words

FryGirl

Well-known Member
Joined
Nov 11, 2008
Messages
1,364
Office Version
  1. 365
  2. 2016
Platform
  1. Windows
I found this macro which works fine for one word, but not sure how not modify for changing an array of words.

Right now the one word within the string I'm looking for is "DET:", but I'd like to add many others.

Could somebody help me with the next step?
Code:
Sub ReplaceStr()
    Dim OriVal As String, RepWhat As String, RepWith As String, TempStr As String
    Dim Cell As Range, Rng As Range
    Dim RepLen As Integer
   
    Application.ScreenUpdating = False
    Set Rng = Range(Range("A2"), Range("A" & Rows.Count).End(xlUp))
    
    RepWhat = "DET:"
    RepWith = "Det:"
    RepLen = Len(RepWhat)

        For Each Cell In Rng
            OriVal = Cell.Value

            Do Until InStr(OriVal, RepWhat) = 0
                TempStr = TempStr & Left(OriVal, InStr(OriVal, RepWhat) - 1) & RepWith
                OriVal = Right(OriVal, Len(OriVal) - ((InStr(OriVal, RepWhat) - 1) + RepLen))
            Loop

            Cell.Value = TempStr & OriVal

            TempStr = ""
            OriVal = ""

        Next Cell
    
    Application.ScreenUpdating = True

End Sub
 

Excel Facts

How can you turn a range sideways?
Copy the range. Select a blank cell. Right-click, Paste Special, then choose Transpose.
FryGirl,

1. What version of Excel and Windows are you using?

2. Are you using a PC or a Mac?


Can you display your search words, and, their replacements (something like this):

"DET:", "Det:"
 
Upvote 0
FryGirl,

We could probably create a macro that does not loop thru your rows.

Can we see what your raw data looks like.

In a separate worksheet you could list in column A the search word, and, in column B the replacement word.


To start off, and, so that we can get it right on the first try:

Can you post a screenshot of the actual raw data worksheet?

And, can you post a screenshot of the worksheet results (manually formatted by you) that you are looking for?

To post a small screen shot (NOT a graphic, or, picture) try one of the following:

Excel Jeanie
Download

MrExcel HTML Maker
https://onedrive.live.com/?cid=8cffdec0ce27e813&sc=documents&id=8CFFDEC0CE27E813!189

Borders-Copy-Paste
http://www.mrexcel.com/forum/about-board/444901-how-create-table-like-aladin.html#post2198045

To test the above:
Test Here


Or, you can upload your workbook to Box Net,
sensitive data changed
mark the workbook for sharing
and provide us with a link to your workbook.
 
Last edited:
Upvote 0
Hi Hiker95,

I'm using 2007 and a PC.

Not sure exactly what you mean about displaying the search words. Do you mean can I list them here?

I'm at work and I can't get to any of those HTML posting methods. The clamps are tight here.
 
Upvote 0
FryGirl,

Can you display all your search words, and, their replacements (something like this):

"DET:", "Det:"


And, it would really help if we could see some of the strings that would contain all of the search words>
 
Upvote 0
Hi Hiker95,

Sorry for the delay...work...gets in the way of the fun stuff.

Anyway, found a way to get some HTML posted...

And here are some samples of the words. First column, "what it is now" and second column, "what I would like"

Data Range
E​
F​
2​
Aetc​
AETC​
3​
Af​
AF​
4​
Occ​
OCC​
5​
And​
and​
6​
Of​
of​
7​
DET​
Det​
8​
Afelm​
AFELM​
9​
Nav​
NAV​
10​
Nco​
NCO​
11​
Rotc​
ROTC​
12​
Nw​
NW​
13​
Hq​
HQ​


And here are some samples of the strings. First column, "what it is now" and second column, "what I would like"

Data Range
A​
B​
1​
Description​
2​
Aetc Civ Engineer Flight​
AETC Civ Engineer Flight​
3​
Af Occ Measurement Squadron​
AF OCC Measurement Squadron​
4​
Aetc Program Mgmt Flight​
AETC Program Mgmt Flight​
5​
Air Educ And Trng Command OL:A5A8​
Air Educ And Trng Command OL:A5A9​
6​
Air Educ And Trng Command OL:000D​
Air Educ And Trng Command OL:000D​
7​
Aetc Studies & Ana Squadron​
AETC Studies & Ana Squadron​
8​
Aetc Computer Sys Squadron​
AETC Computer Sys Squadron​
9​
Af Inst Of Tech Institute​
AF Inst Of Tech Institute​
10​
Af Inst Of Tech Institute DET:0001​
AF Inst Of Tech Institute Det:0002​
11​
Af Research Institute​
AF Research Institute​
12​
Air University University DET:0001​
Air University University Det:0002​
13​
Afelm Nav Postgrad Element​
AFELM NAV Postgrad Element​
14​
Commun Col Af College​
Commun Col AF College​
15​
Senior Nco Academy School​
Senior NCO Academy School​
16​
Air Force Rotc Corps​
Air Force ROTC Corps​
17​
Afrotc Northeast Region OL:NE00​
AFROTC Northeast Region OL:NE01​
18​
Afrotc Nw Region OL:NW00​
AFROTC NW Region OL:NW01​
19​
Hq Af Recruiting Service OL:000A​
HQ AF Recruiting Service OL:000A​

If at all possible, just like the code posted above, can these updates be done in column A? If it requires a helper column that would be fine as the helper column could just be pasted on top of column A.
 
Last edited:
Upvote 0
FryGirl,

Here is a macro solution for you to consider.

For the macro to work correctly you should swap the Of of , to of Of - see the Yellow cells.

Sample raw data in worksheet Data:


Excel 2007
ABCDEF
1DescriptionSearchReplace
2Aetc Civ Engineer FlightAetcAETC
3Af Occ Measurement SquadronAfAF
4Aetc Program Mgmt FlightOccOCC
5Air Educ And Trng Command OL:A5A8Andand
6Air Educ And Trng Command OL:000DofOf
7Aetc Studies & Ana SquadronDETDet
8Aetc Computer Sys SquadronAfelmAFELM
9Af Inst Of Tech InstituteNavNAV
10Af Inst Of Tech Institute DET:0001NcoNCO
11Af Research InstituteRotcROTC
12Air University University DET:0001NwNW
13Afelm Nav Postgrad ElementHqHQ
14Commun Col Af College
15Senior Nco Academy School
16Air Force Rotc Corps
17Afrotc Northeast Region OL:NE00
18Afrotc Nw Region OL:NW00
19Hq Af Recruiting Service OL:000A
20
Data


After the macro:


Excel 2007
ABCDEF
1DescriptionSearchReplace
2AETC Civ Engineer FlightAetcAETC
3AF OCC Measurement SquadronAfAF
4AETC Program Mgmt FlightOccOCC
5Air Educ and Trng Command OL:A5A8Andand
6Air Educ and Trng Command OL:000DofOf
7AETC Studies & Ana SquadronDETDet
8AETC Computer Sys SquadronAfelmAFELM
9AF Inst Of Tech InstituteNavNAV
10AF Inst Of Tech Institute Det:0001NcoNCO
11AF Research InstituteRotcROTC
12Air University University Det:0001NwNW
13AFELM NAV Postgrad ElementHqHQ
14Commun Col AF College
15Senior NCO Academy School
16Air Force ROTC Corps
17AFROTC Northeast Region OL:NE00
18AFROTC NW Region OL:NW00
19HQ AF Recruiting Service OL:000A
20
Data


Please TEST this FIRST in a COPY of your workbook (always make a backup copy before trying new code, you never know what you might lose).

1. Copy the below code
2. Open your NEW workbook
3. Press the keys ALT + F11 to open the Visual Basic Editor
4. Press the keys ALT + I to activate the Insert menu
5. Press M to insert a Standard Module
6. Where the cursor is flashing, paste the code
7. Press the keys ALT + Q to exit the Editor, and return to Excel
8. To run the macro from Excel press ALT + F8 to display the Run Macro Dialog. Double Click the macro's name to Run it.

Code:
Option Compare Text
Sub FindReplace()
' hiker95, 02/24/2015, ME838239
Dim sr, i As Long
Dim c As Range
Application.ScreenUpdating = False
With Sheets("Data")
  sr = .Range("E2:F" & .Cells(Rows.Count, "E").End(xlUp).Row)
  For Each c In .Range("A2:A" & .Cells(Rows.Count, "A").End(xlUp).Row)
    For i = LBound(sr) To UBound(sr)
      If InStr(c, sr(i, 1)) Then
        c = Replace(c, sr(i, 1), sr(i, 2))
      End If
    Next i
  Next c
End With
Application.ScreenUpdating = True
End Sub

Before you use the macro with Excel 2007 or newer, save your workbook, Save As, a macro enabled workbook with the file extension .xlsm, and, answer the "do you want to enable macros" question as "yes" or "OK" (depending on the button label for your version of Excel) the next time you open your workbook.

Then run the FindReplace macro.
 
Upvote 0
Thanks hiker95

I'll test this tmw at work and then provide feedback. Thank you very much for your time.

I noticed "Dim sr". Does that mean it is dimmed as a variant?
 
Upvote 0
FryGirl,

Thanks hiker95

I'll test this tmw at work and then provide feedback. Thank you very much for your time.

You are very welcome.

Will check tomorrow for your next reply.

I noticed "Dim sr". Does that mean it is dimmed as a variant?

Yes, I read range E2:F13 into the array, and, use it to search, and, replace.

I loop thru the array for each cell in column A.
 
Upvote 0
Good Morning Hiker95,

All is testing out great so far. One tweak so far. I asked for Af to be AF, but forgot to include Aircraft which turned out as AircrAFt. To fix, just added a space after the search and replace for Af/AF and all worked.

Since this is part of a bigger macro, it may work best to write the search/replace values onto the spreadsheet as an array.

I tried

Code:
  .Range("E2:E18").Value = Array("Aetc", "Af ", "Occ", "And", "of", "DET", "Afelm", "Nav", "Nco", "Rotc", "Nw", "Hq", "Def", "Usaf", "Afrotc", "Dod", "Dli")
  .Range("F2:F18").Value = Array("AETC", "AF ", "OCC", "and", "Of", "Det", "AFELM", "NAV", "NCO", "ROTC", "NW", "HQ", "DEF", "USAF", "AFROTC", "DoD", "DLI")

but this does not like spreading out vertically, but of course if I change to something like .Range("E1:U1") the array reads in correctly.

Can this be done? Reading the array onto the spreadsheet horizontally?
 
Upvote 0

Forum statistics

Threads
1,215,753
Messages
6,126,677
Members
449,327
Latest member
John4520

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