删除单元格中字符之间的空格,但前提是两个单个字符之间存在空格

删除单元格中字符之间的空格,但前提是两个单个字符之间存在空格

在10000行excel中处理,删除单元格中字符之间的空格,但前提是两个单个字符之间存在空格。

P J A JACKSON AND SONS

应该成为

PJA JACKSON AND SONS

JOHNSON AND SMITH

应该保留

JOHNSON AND SMITH

答案1

这可以使用正则表达式和查找和替换来完成。在“开始”选项卡的“编辑”组中,单击“替换”以打开“查找和替换”对话框,如果您没有看到“使用通配符”复选框,请单击“更多”,然后选中该复选框。

查找: (<[^\s]>) (<[^\s]>) 替换: \1\2

这将匹配两个单个字符之间的所有空格,然后将其删除。希望这对您有所帮助!

答案2

选择您想要处理的单元格并运行此宏:

Sub formatter()
  Dim txt As String, i As Long
  Dim r As Range, txt2 As String

  For Each r In Selection
    txt = r.Text
    If InStr(1, txt, " ") > 0 Then
      ary = Split(txt, " ")
      txt2 = ary(0)
      For i = 1 To UBound(ary)
        If Len(ary(i - 1)) = 1 And Len(ary(i)) = 1 Then
          txt2 = txt2 & ary(i)
        Else
          txt2 = txt2 & " " & ary(i)
        End If
      Next i
      If txt2 <> txt Then
        r.Value = txt2
      End If
    End If
  Next r
End Sub

答案3

这是一个使用 VBA 的解决方案。

使用方法:

Alt+ F11- 将代码复制到ThisWorkbook

您可以从以下位置运行代码:MS Excel -View选项卡 - Macros(热键:Alt+ F8
或者您可以为其分配一个按钮。

默认情况下,宏将应用于每个使用的单元格。如果您需要修改,只需发表评论,我将使用请求的修改更新答案。

Sub remove_spaces()

Dim actives As String
Dim c As Range
Dim myStr As String
Dim myArray() As String
Dim wordsc As String
Dim wcount As Integer
Dim newStr As String

actives = ActiveSheet.Name


For Each c In Sheets(actives).UsedRange.Cells

    If c <> "" Then     
        wordsc = c
        wcount = WordCount(wordsc)

        ReDim myArray(wcount)

        myStr = c
        myArray = Split(myStr, " ")
        c = ""
        newStr = myArray(0)

        For i = 1 To wcount - 1
            MsgBox myArray(i)
            If Len(myArray(i - 1)) = 1 And Len(myArray(i)) = 1 Then

                newStr = newStr & myArray(i)

            Else

                newStr = newStr & " " & myArray(i)

            End If

        c = newStr

        Next i

    End If

Next c



End Sub

Function WordCount(fullText As String) As Long
Dim words() As String
Dim firstLetter As String
Dim i As Long

  words = Split(fullText)

  For i = LBound(words) To UBound(words)
    firstLetter = UCase$(Left$(words(i), 1))
    ' if it's alphabetic, +1 word
    If firstLetter Like "[A-Za-z]" Then
      WordCount = WordCount + 1
    End If
  Next i

End Function

相关内容