Reputation: 73
I've written some macros to format a load of data into the same accepted format, the program we pull from refuses to pull the data how we want it but in theory it wouldn't be hard to change in Excel.
The way it is set to run is to have separate macros for the modifiers and then a 'Run All' macro that just does a Call to them all.
Currently I have:
Sub ReplaceTitleMs()
'
' Strips Mrs from Headteacher Name
'
'
'
Columns("V").Select
Cells.Replace What:="Ms ", Replacement:="", LookAt:=xlPart, SearchOrder _
:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
End Sub
But when I run this, it strips Ms from the whole sheet and one column requires Ms to still be in the Cells (this is column W)
An example of the data is effectively:
Ms Helen Smith
Ms Brenda Roberts
Ms Kirsty Jones
But there are many other titles being used so I would like to just run a Find and Replace on the column that has to be selected by the macro.
The macro works find on the column I want it to...I just need to restrict it to that column!
Upvotes: 6
Views: 89751
Reputation: 8816
press the "ALT + F11
" keys shortcut (i.e. hold ALT
key down and press F11
key at last release both) to open the Microsoft Visual Basic for Applications window.
Click "Insert > Module
" (i.e. from "Insert
" menu click "Module
"), and paste the following code in the Module Window.
Sub ReplaceInSelection()
Dim rng As Range
Dim workRng As Range
Dim find$
Dim replace$
On Error Resume Next
xTitleId = "KutoolsforExcel"
Set workRng = Application.Selection
Set workRng = Application.InputBox("Range", "Select Range", workRng.Address, Type:=8)
find = Application.InputBox("Find:", "Select what to find")
replace = Application.InputBox("Replace with:", "Select replacement")
For Each rng In workRng
If rng.Value = find Then
rng.Value = replace
End If
Next
End Sub
ALT + F8
" key (or just F5
in older excel), to run the code click run while "ReplaceInSelection
" is selectedOK
find
replace
any occurrence of what was foundall done! the selected cells have been searched for what you specified to find
and was changed with again what you specified to replace with
.
Upvotes: 0
Reputation: 55692
Based on your data (which is properly capitilised), to avoid false matches you should set MatchCase
to True to avoid culling the likes of
Mrs Nancy Adams
to Mrs Nancy Ada
Columns("V").Replace "Ms ", vbNullString, xlPart, xlByRows, True
To be completely bullet-proof, you would either
AutoFilter
for the detection and removalFind
and FindNext
, then remove only the first three characters where the match is correctUpvotes: 10
Reputation:
You need to properly qualify the range for the Replace()
method
Sub ReplaceTitleMs()
Columns("V").Replace What:="Ms ", _
Replacement:="", _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
MatchCase:=False, _
SearchFormat:=False, _
ReplaceFormat:=False
End Sub
Upvotes: 16