I want to replace the numbers 91, 92, 93, 94, 99 with 91H, 92H, 93H, 94H, 99H. But every time I run the macro a second time, the macro adds another H to the number and it looks like 91H H for example. I can't find a solution for this. I don't want that the macro adds another H to the number. I want that the macro only adds a H to the new values, not to the ones that have already been changed.
Columns("D").Replace What:="92", _
Replacement:="92H", _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
MatchCase:=False, _
SearchFormat:=False, _
ReplaceFormat:=False
Columns("D").Replace What:="93", _
Replacement:="93H", _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
MatchCase:=False, _
SearchFormat:=False, _
ReplaceFormat:=False
Columns("D").Replace What:="91", _
Replacement:="91H", _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
MatchCase:=False, _
SearchFormat:=False, _
ReplaceFormat:=False
Columns("D").Replace What:="94", _
Replacement:="94H", _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
MatchCase:=False, _
SearchFormat:=False, _
ReplaceFormat:=False
Columns("D").Replace What:="99", _
Replacement:="99H", _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
MatchCase:=False, _
SearchFormat:=False, _
ReplaceFormat:=False
I didn't post the whole VBA code because it's a little bit long.
I think of a workaround. Add codes before the macro to replace 91H, 92H, 93H, 94H, 99H with 91, 92, 93, 94, 99. What the new macro would do is:
A. "91H": remove "H" and add "H", ie do nothing
B. "91": dont fit into first part, "H" will be added in 2nd part
This should work for any text seen.
In general, you are repeating lots of code. This should be avoided. A way to do it is like this:
Option Explicit
Sub ReplaceSomething(columnName As String, lookFor As String, replaceWith As String)
Dim rngCol As Range
Dim rngCells As Range
If WorksheetFunction.CountA(Columns(columnName)) = 0 Then Exit Sub
Set rngCol = Columns(columnName).SpecialCells(2)
If rngCol Is Nothing Then Exit Sub
For Each rngCells In rngCol
If rngCells = lookFor Then
rngCells = replaceWith
End If
Next rngCells
End Sub
Sub TestMe()
ReplaceSomething "A", "H", "H1"
ReplaceSomething "B", "H", "H1"
ReplaceSomething "D", "H", "H1"
End Sub
Thus you would be giving the Column Name as an argument of the function ReplaceSomething and it will run for columns A, B and C.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.