vba 如何检查excel单元格值是否有空格... excel 2007

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8212637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 14:30:48  来源:igfitidea点击:

How to check that excel cell value has spaces... excel 2007

vbaexcel-2007spaces

提问by user999896

I have an Excel file that contains some values. I need to check if a cell value contains spaces. For example, sometimes a user will write some values in the cell but mistakenly press Enter or Space in the cell. I want to see if the cell value has spaces inside... Please tell me how to do this.

我有一个包含一些值的 Excel 文件。我需要检查单元格值是否包含空格。例如,有时用户会在单元格中写入一些值,但在单元格中错误地按了 Enter 或 Space。我想看看单元格值里面是否有空格...请告诉我如何做到这一点。

Thanks

谢谢

回答by JimmyPena

Let's say I type "ABC " in cell A1 (ABC followed by a space). Either of these formulas should help:

假设我在单元格 A1 中键​​入“ABC”(ABC 后跟一个空格)。这些公式中的任何一个都应该有帮助:

=LEN(A1)=LEN(TRIM(A1))

=EXACT(A1,TRIM(A1))

For a VBA version:

对于 VBA 版本:

Function HasSpaces(rng As Excel.Range) As Boolean
  HasSpaces = Not (Len(rng.Value) = Len(Trim$(rng.Value)))
End Function

Sample usage:

示例用法:

Sub tst()
  Debug.Print HasSpaces(Range("A1"))
End Sub