JHizzal
JHizzal

Reputation: 651

Wildcard Character in String

I have a spreadsheet I receive regularly with a large number of cells containing names. Some cells have a full name including a middle initial with a period.

For example:

Springer, Jerry A.

Every now and then though the sheet I receive will have the following:

Springer, Jerry .

I need to get rid of those middle initials but also check to make sure that I just delete the "." if it's there.

Forgive me for my lack of proper logic, but I have the following ca-ca sub:

Sub DeleteMiddleI()
Dim nr1, nr2 As Range
Dim col As Integer

col = 1
Set nr1 = Cells(65536, col).End(xlUp)
Set nr2 = Cells(col, 1)

Do While nr2 <> nr1
    'Check to be sure the cell isn't empty
    If Len(nr2) <> 0 Then
         'Check to see if the last character is a "."
         If Right$(nr2, 1) = "." Then
            'Check and be sure there is a character before the "."
            If InStr(1, nr2.Text, "[A-Z].") > 0 Then '<<<<<<CODE BREAKAGE
                nr2 = Left$(nr2, Len(nr2) - 3)
            End If
         End If
    End If

    col = col + 1
    Set nr2 = Cells(col, 1)
Loop

End Sub

It breaks on the

If InStr(1, nr2.Text, "[A-Z].") > 0 Then

I feel stupid...but what am I missing?

Upvotes: 2

Views: 3778

Answers (2)

Siddharth Rout
Siddharth Rout

Reputation: 149277

Would this help? This would replace all the " ." with nothing.

Option Explicit

Sub Sample()
    Sheets("Sheet1").Cells.Replace What:=" .", Replacement:="", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
End Sub

EDIT

What did you mean by removing initials part? Do you mean changing Springer, Jerry A. to Springer, Jerry or Springer, Jerry . to Springer, Jerry

If yes, then would this help?

Option Explicit

Sub Sample()
    Dim LastRow As Long
    Dim Pos As Long, i As Long

    With Sheets("Sheet1")
        LastRow = .Range("A" & Rows.Count).End(xlUp).Row

        For i = 1 To LastRow
            Pos = InStr(1, .Range("A" & i).Value, ", ") + 2
            If Pos > 2 Then
                Pos = InStr(Pos, .Range("A" & i).Value, " ")
                If Pos > 0 Then .Range("A" & i).Value = Mid(.Range("A" & i).Value, 1, Pos - 1)
            End If
        Next i
    End With
End Sub

Upvotes: 4

bendataclear
bendataclear

Reputation: 3850

Could you change the if test from:

If Right$(nr2, 1) = "." Then

to

If (Right$(nr2, 1) = "." AND Left$(nr2, 1) <> "." ) Then

Upvotes: 0

Related Questions