1

I know that the TRIM function as worksheet function and as VBA function returns different results:

  • the worksheet function removes all spaces from a text string except for single spaces between words
  • while the VBA function only removes leading and trailing spaces.

There is a way to emulate the VBA behavior with worksheet functions, WITHOUT a custom VBA function?

4

3 回答 3

5

Using only worksheet functions you could try this for a text string in A1:

=REPLACE(LEFT(A1,MATCH(2,1/(MID(A1,MMULT(ROW(INDIRECT("1:"&LEN(A1))),1),1)<>" "))),1,FIND(LEFT(TRIM(A1)),A1)-1,"")

Finding the position of the last character that's not a space is not straightforward due to the lack of string reverse worksheet functions.

If you don't want to use VBA it's much simpler to use Data|Text to Columns with the options:

  1. Fixed Width
  2. No break lines
  3. Destination: B1

which also removes leading and trailing spaces.

于 2012-06-11T10:07:10.520 回答
2

the worksheet function removes all spaces from a text string except for single spaces between words

No that is not completely true :) Worksheet TRIM function does not remove the nonbreaking space character (&nbsp;). To remove the nonbreaking space character, you have a different function called CLEAN()

If you want to use the Worksheet Function Trim in VBA then you can use it like this

Application.WorksheetFunction.Trim(Range("A1").Value)

In Excel Worksheet you can use =TRIM()

于 2012-06-11T08:53:40.360 回答
0

You can write a function in VBA that you can refer to in your worksheet.

For example:

Public Function MyTrim(text As String) As String    
    MyTrim = Trim(text)    
End Function

Then in your worksheet, assuming the text you want to trim is in cell A1:

=MyTrim(A1)
于 2012-06-11T08:58:19.783 回答