Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel 如何删除文本之间的空格?_Excel_Vba - Fatal编程技术网

Excel 如何删除文本之间的空格?

Excel 如何删除文本之间的空格?,excel,vba,Excel,Vba,为什么trim在VBA中不起作用 for i = 3 to 2000 activesheet.cells(i,"C").value = trim(Activesheet.cells(i,"C").value) next i 无法删除文本之间的空格 hiii how ' even after trying trim the o/p is still these hiii how 我需要删除额外的空间,所以我找到了修饰符>代码>但是它不工作

为什么trim在VBA中不起作用

for i = 3 to 2000
activesheet.cells(i,"C").value = trim(Activesheet.cells(i,"C").value)
next i
无法删除文本之间的空格

 hiii              how ' even after trying trim the o/p is still these
 hiii              how

我需要删除额外的空间,所以我找到了<代码>修饰符>代码>但是它不工作,而<>代码> Ltrim和<代码> rTrim是。

修剪在开始和结束时移除额外的空间,而不是在字符串的中间。

Function CleanSpace(ByVal strIn As String) As String
    strIn = Trim(strIn)

  ' // Replace all double space pairings with single spaces
    Do While InStr(strIn, "  ")
        strIn = Replace(strIn, "  ", " ")
    Loop

    CleanSpace = strIn
End Function

另外,这不是删除空格的最有效方法。我不会在很多非常长的字符串上使用,也不会在紧密的循环中使用。它可能适合您的情况。

与Excel不同。改用

Excel Trim将删除除单词之间的单个空格以外的所有空格。VBA修剪将删除前导和尾随空格


感谢MS为不同的功能使用相同的关键字

我知道这个问题很老,但我刚找到它,我想我应该添加我用来删除VBA中多个空格的内容

cleanString = Replace(Replace(Replace(Trim(cleanString), _ 
 " ", " |"), "| ", ""), " |", " ") 'reduce multiple spaces chr(32) to one

我知道这是相当古老的,但我想我应该添加其他东西,而不是所有这些替代选项

在VBA中使用trim(或trim$)将删除前导空格和尾随空格,这与Excel中的=trim不同


如果需要从字符串中删除空格(如下所述,不一定是所有空格),只需使用
工作表函数。Trim

有时看起来像空格的不是空格而是无法显示的字符。 使用ASC函数获取字符的整数值。然后使用以下代码:

Function CleanSpace(ByVal StrIn As String) As String
    StrIn = Trim(StrIn)

  ' Searches string from end and trims off excess ascii characters

  Dim StrLength As Integer
  Dim SingleChar As Integer
  Dim StrPosition As Integer

  SingleChar = 1

  StrLength = Len(StrIn)
  StrPosition = StrLength - 1

    Do Until Asc(Mid(StrIn, StrPosition, SingleChar)) <> 0
        StrPosition = StrPosition - 1
    Loop
  StrIn = Mid(StrIn, 1, StrPosition)

End Function
函数CleanSpace(ByVal StrIn作为字符串)作为字符串
StrIn=修剪(StrIn)
'从结尾搜索字符串并修剪多余的ascii字符
Dim StrLength为整数
作为整数的Dim SingleChar
作为整数的Dim StrPosition
SingleChar=1
StrLength=Len(StrIn)
StrPosition=StrLength-1
直到Asc(中间(StrIn,StrPosition,SingleChar))0
StrPosition=StrPosition-1
环
StrIn=Mid(StrIn,1,StrPosition)
端函数

如果您熟悉集合,我曾经编写过一个快速代码,可以处理整个工作表,即使它很大,也可以删除所有单元格中的所有双空格、前导空格和尾随空格以及不可见字符。只是要注意它会删除你的文本格式,我也没有做太多的测试,它的详尽,但它为我的短期任务,工作速度快

这是一个辅助函数,用于将工作表加载到集合中

Function LoadInCol() As Collection

Dim currColl As Collection
Dim currColl2 As Collection

Set currColl = New Collection
Set currColl2 = New Collection

With ActiveSheet.UsedRange
    LastCol = .Columns(.Columns.Count).Column
    lastrow = .Rows(.Rows.Count).Row
End With

For i = 1 To lastrow

    For j = 1 To LastCol
        currColl.Add Cells(i, j).Value
    Next

    currColl2.Add currColl
    Set currColl = New Collection

Next

    Set LoadInCol = currColl2

End Function
这是删除空格的主要子元素

Sub RemoveDSpaces()

'Removes double spaces from the whole sheet

Dim Col1 As Collection
Dim Col2 As Collection
Dim Col3 As Collection

Dim StrIn As String

Dim Count As Long

Set Col1 = New Collection
Set Col2 = New Collection
Set Col3 = New Collection


Set Col1 = LoadInCol()

Count = Col1.Count

i = 0

For Each Item In Col1

i = i + 1
If i >= Count + 1 Then Exit For

    Set Col2 = Item

    For Each Item2 In Col2

        StrIn = WorksheetFunction.Clean(Trim(Item2))

        Do Until InStr(1, StrIn, "  ", vbBinaryCompare) = 0
            StrIn = Replace(StrIn, "  ", Chr(32))
        Loop

        Col3.Add StrIn

    Next

Col1.Remove (1)
Col1.Add Col3
Set Col3 = New Collection

Next

'Store Results

Cells.ClearContents

    Z = 1
    m = 1
    Set Col3 = New Collection

    For Each Item In Col1

        Set Col3 = Item

            For Each Item2 In Col3
                Cells(Z, m) = Item2
                m = m + 1
            Next

            m = 1
            Z = Z + 1

    Next

End Sub

你所有的其他函数都留下了空白吗

快点

CleanUltra删除所有空白和不可打印字符,包括其他函数留下的空白

我希望你觉得这有用。欢迎任何改进

Function CleanUltra( _
       ByVal stringToClean As String, _
       Optional ByVal removeSpacesBetweenWords As Boolean = False) _
        As String
' Removes non-printable characters and whitespace from a string


' Remove the 1 character vbNullChar. This must be done first
'  if the string contains vbNullChar
    stringToClean = Replace(stringToClean, vbNullChar, vbNullString)

    ' Remove non-printable characters.
    stringToClean = Application.Clean(stringToClean)

    ' Remove all spaces except single spaces between words
    stringToClean = Application.Trim(stringToClean)

    If removeSpacesBetweenWords = True Then _
       stringToClean = Replace(stringToClean, " ", vbNullString)

    CleanUltra = stringToClean
End Function
下面是它的用法示例:

Sub Example()
    Dim myVar As String
    myVar = " abc d e  "

    MsgBox CleanUltra(myVar)
End Sub
我运行了一个测试来验证函数是否删除了所有空格
vbNullChar
特别狡猾。在使用
CLEAN
TRIM
函数阻止它们删除
vbNullChar
之后的所有字符之前,我必须先将函数设置为删除它

Sub Example()
    Dim whitespaceSample As String
    Dim myVar As String

' Examples of various types of whitespace
'  (vbNullChar is particularly devious!)
    whitespaceSample = vbNewLine & _
                       vbCrLf & _
                       vbVerticalTab & _
                       vbFormFeed & _
                       vbCr & _
                       vbLf & _
                       vbNullChar

    myVar = "     1234" & _
            whitespaceSample & _
            "     56      " & _
            "789     "

    Debug.Print "ORIGINAL"
    Debug.Print myVar
    Debug.Print "Character Count: " & Len(myVar)


    Debug.Print
    Debug.Print "CLEANED, Option FALSE"


    Debug.Print CleanUltra(myVar)
    Debug.Print CleanUltra(myVar, False)
    '   Both of these perform the same action.  If the optional parameter to
    '   remove spaces between words is left blank it defaults to FALSE.
    '   Whitespace is removed but spaces between words are preserved.
    Debug.Print "Character Count: " & Len(CleanUltra(myVar))


    Debug.Print
    Debug.Print "CLEANED, Option TRUE"

    Debug.Print CleanUltra(myVar, True)
    '   Optional parameter to remove spaces between words is set to TRUE.
    '   Whitespace and all spaces between words are removed.
    Debug.Print "Character Count: " & Len(CleanUltra(myVar, True))

End Sub

我的相关问题是,最后一个字符是一个chr(160)——一个不间断的空格。所以trim(replace(Str,chr(160),“”))就是解决方案。

当您调用trim()时,VBA实际上是在调用Strings.trim()。此函数仅删除前导空格和尾随空格。要删除字符串中过多的空格,请使用

Application.Trim()

我知道这个问题由来已久,但我只想分享我的解决方案,如何处理和解决这个问题

也许您可能想知道为什么有时候
修剪功能不起作用,请记住,它只会删除空格,空格相当于ASCII 32。因此,如果这些ASCII 13ASCII 10存在于字符串值的开头结尾,则
修剪功能将无法对其起作用

Function checkASCIItoBeRemoved(myVal) As String

Dim temp As String
temp = Replace(Trim(myVal), Chr(10), Empty)
temp = Replace(temp, Chr(13), Empty)
checkASCIItoBeRemoved = temp

End Function
这段代码对我有效,顺便说一句,如果这对你来说可能不起作用,那么试着检查你字符串值的ASCII,因为它可能有另一个不可见的特殊字符,我的代码中可能没有替换它,请添加它以起作用。

不可见的特殊字符

真的吗?非常感谢,我该怎么做才能删除
Replace(Activesheet.cells(i,“C”).value“”)之间的空格呢
将删除字符串中的所有空格。不确定这是否是您想要的……您是否阅读了有关
Trim
功能的VBA帮助?因为这就是
Trim
现在应该做的事情…其实没那么重要,但是您可以删除活动表部分。另外,Excel中看似空白的字符不是通常的ASCII 32,而是其他字符,例如ASCII 255。在这些情况下,
trim
replace”“
将不起作用。一个正则表达式查找多个空格并用一个空格替换它会更有效吗?(如果你认为可以的话,只是建议一种更有效的方式)看看我的答案。这就像使用Excel的函数而不是VBAs版本一样简单(它们产生不同的结果)。+1。我不知道。同意:Trim关键字的重载有点让人困惑。希望我们能让VBA函数像Excel WS一样工作function@Jorge当前位置Application.Trim.谢谢我不能接受你的回答,但我会为你找到适合我的答案而投票再次感谢!非常感谢,我正在努力获取标签空间的代码。黄金解决方案!谢谢