在VBA 7.0中修剪换行符和空格

时间:2016-12-23 18:06:19

标签: vba

修剪(在MS-Access 2010的VBA中)不会删除vbCrLfs,只删除空格。在即时窗口中,我得到了

? Len(vbCrLf & "a" & vbCrLf & "b" & vbCrLf)
 8 

? Len(Trim(vbCrLf & "a" & vbCrLf & "b" & vbCrLf))
 8 

但是对于空格:

? Len(" " & "a" & " " & "b" & " ")
 5 

? Len(Trim(" " & "a" & " " & "b" & " "))
 3 

如何进行仅在末端删除vbCrLF的修剪?

2 个答案:

答案 0 :(得分:1)

如果您不介意删除所有新行(而不仅仅是边缘),您可以这样做:

myStr = Application.clean(Application.trim(myStr))

对于模仿修剪功能,你需要测试字符串边缘的每个字符:

Function TrimNewLines(mtStr As String) As String
    Dim pattern As String, c As String
    Dim i As Integer: i = 1
    pattern = "[" & Chr(10) & Chr(13) & "]"
    c = Mid(mtStr, i, 1)
    Do While c Like pattern
        i = i + 1
        c = Mid(mtStr, i, 1)
    Loop
    mtStr = Mid(mtStr, i, Len(mtStr))
    i = Len(mtStr)
    c = Mid(mtStr, i, 1)
    Do While c Like pattern
        i = i - 1
        c = Mid(mtStr, i, 1)
    Loop
    mtStr = Mid(mtStr, 1, i)
    TrimNewLines = mtStr
End Function

答案 1 :(得分:-1)

这似乎已经成功了:

Public Function trimNewlinesAndSpaces(chaine As String) As String
    chaine = Trim(chaine)

    Do While (left(chaine, 2) = vbCrLf) Or right(chaine, 2) = vbCrLf
        If left(chaine, 2) = vbCrLf Then
            chaine = right(chaine, Len(chaine) - 2)
        End Ifj

        If right(chaine, 2) = vbCrLf Then
            chaine = left(chaine, Len(chaine) - 2)
        End If

        chaine = Trim(chaine)
    Loop

    trimNewlinesAndSpaces = chaine
End Function