我正在Excel VBA中逐行读取文件。
我有一些字符串,例如,
" ooo"
" ooo "
我想找到字符串前面的空格数。如果我使用Trim,它会从字符串的后面和前面删除空格。
答案 0 :(得分:6)
您可以使用LTrim
和RTrim
功能。 - 我认为这比循环字符串和进行字符比较更快。
Public Function NumberOfLeadingSpaces(ByVal theString As String) As Long
NumberOfLeadingSpaces = Len(theString) - Len(LTrim(theString))
End Function
Public Function NumberOfTrailingSpaces(ByVal theString As String) As Long
NumberOfTrailingSpaces = Len(theString) - Len(RTrim(theString))
End Function
答案 1 :(得分:2)
Function test(s As String) As Integer
Dim str As String
str = "[abcdefghijklmnopqrstuvwxyz0123456789]"
Dim spaceCounter As Integer
For i = 1 To Len(s)
If Not Mid(s, i, 1) Like str Then
spaceCounter = spaceCounter + 1
Else
Exit For
End If
Next i
test = spaceCounter
End Function
受欢迎的请求:为什么要使用此功能而不是Trim
,LTrim
等?
好吧,总结the full explanation,并非所有空格都可以使用Trim
删除。但是这些函数将删除它们。
考虑这个例子(为了说明目的,我会借用PhilS' solution):
Sub testSpaceRemoval()
Dim str1 As String
str1 = " " & Chr(32) & Chr(160) & "a"
Debug.Print Chr(34) & str1 & Chr(34)
Debug.Print NumberOfLeadingSpaces(str1)
Debug.Print test(str1)
End Sub
结果:
" a"
2
3
在这里我们可以看到字符串显然包含3个空格,但使用LTrim
的解决方案只计算了2个。
那么,用什么?
嗯,这取决于。如果你有一个数据集,你知道你不会得到非破坏的字符,请尽可能多地使用Trim
!如果您认为自己可以获得不间断的字符,仅仅Trim
就不够了。
要注意的字符,引自上面链接的解释:
前导,尾随或多个嵌入空格字符(Unicode字符集值32和160)或非打印字符(Unicode字符集值0到31,127,129,141,143,144和157)< / p>
Trim
可以移除chr(32)
(如上所示)但不移除chr(160)
,因为32 is the regular space and 160 is a non-breaking space。
如果你是一个掩饰背后的坚持者,请考虑这个完整的解决方案:
Function cleanSpecialCharacters(str As String) As String
bannedChars = Chr(127) & "," & Chr(129) & "," & Chr(141) & "," & Chr(143) & "," & Chr(144) & "," & Chr(157) & "," & Chr(160)
str = Application.WorksheetFunction.Clean(str)
str = Application.WorksheetFunction.Trim(str)
For Each c In Split(bannedChars, ",")
str = Replace(str, c, "")
Next
cleanSpecialCharacters = str
End Function
对于OP的特定问题,它必须更加量身定制。
答案 2 :(得分:0)
Sub main()
Dim strng As String
Dim i As Long
strng = " ooo "
i = 1
Do While Mid(strng, i, 1) = " "
i = i + 1
Loop
MsgBox "number of front empty spaces: " & i - 1
End Sub
或使用LTrim
功能:
Sub main2()
Dim strng As String
strng = " ooo "
MsgBox "number of front empty spaces: " & Len(strng) - Len(LTrim(strng))
End Sub
答案 3 :(得分:0)
Sub blanks()
cadena = Cells(1, 1)
i = Len(cadena)
Do Until Mid(cadena, i, 1) <> " "
If Mid(cadena, i, 1) = " " Then contador = contador + 1
i = i - 1
Loop
Cells(2, 1) = contador
End Sub