为什么 VBA 替换函数不能与 Word 和 Excel 中的 CRLF 一起使用

Mic*_*y D 3 vba replace chr

我可以发誓我过去已经剥离了 CRLF,但不确定为什么以下内容不起作用:

myString = "ABC" & vbCrLf & "DEF"
str1 = Replace(myString, vbLf, "")
str2 = Replace(str1, vbCrLf, "")
str3 = Replace(str2, vbNewLine, "") 
MsgBox str3
Run Code Online (Sandbox Code Playgroud)

上面的代码不起作用,结果是:

ABC
DEF
Run Code Online (Sandbox Code Playgroud)
myString = "ABC" & vbCrLf & "DEF"
str1 = Replace(myString, Chr(13), "")
str2 = Replace(str1, Chr(10), "")
MsgBox str2
Run Code Online (Sandbox Code Playgroud)

上面的代码确实有效,结果是:

ABCDEF
Run Code Online (Sandbox Code Playgroud)

解决方案:感谢@ Mat 的回答(第一个代码的问题是我试图删除项目的顺序)VbCrLf 和 VbNewLine 是相同的,并且在删除 VbLf 后尝试删除组合 vbCr+VbLf 将不起作用

Mat*_*don 5

前提是有缺陷的:

myString = "ABC" & vbCrLf & "DEF"
Run Code Online (Sandbox Code Playgroud)

字符串由“ABC”、“ vbCrLf、”和“DEF”组成。

vbCrLfvbCrvbLf,在任何 Windows 机器上都是vbNewLine

当你这样做时:

str1 = Replace(myString, vbLf, "")
Run Code Online (Sandbox Code Playgroud)

您替换vbLf 并保留vbCr角色

str2 = Replace(str1, vbCrLf, "")
Run Code Online (Sandbox Code Playgroud)

然后你替换vbCrLf vbLf已经消失了所以vbCrLf不在字符串中

str3 = Replace(str2, vbNewLine, "") 
Run Code Online (Sandbox Code Playgroud)

然后你替换vbNewLinewhich 基本上和前面的指令做完全一样的事情,结果是一个被剥离vbLf 但仍然包含vbCr.

此代码按预期工作:

Sub Test()
    Dim foo As String
    foo = "foo" & vbCrLf & "bar"
    Debug.Print foo
    foo = Replace(foo, vbNewLine, vbNullString)
    Debug.Print foo
End Sub
Run Code Online (Sandbox Code Playgroud)

就像这样:

Sub Test()
    Dim foo As String
    foo = "foo" & vbNewLine & "bar"
    Debug.Print foo
    foo = Replace(foo, vbNewLine, vbNullString)
    Debug.Print foo
End Sub
Run Code Online (Sandbox Code Playgroud)

或这个:

Sub Test()
    Dim foo As String
    foo = "foo" & vbNewLine & "bar"
    Debug.Print foo
    foo = Replace(foo, vbCrLf, vbNullString)
    Debug.Print foo
End Sub
Run Code Online (Sandbox Code Playgroud)

甚至这个:

Sub Test()
    Dim foo As String
    foo = "foo" & vbNewLine & "bar"
    Debug.Print foo
    foo = Replace(foo, vbCr, vbNullString)
    foo = Replace(foo, vbLf, vbNullString)
    Debug.Print foo
End Sub
Run Code Online (Sandbox Code Playgroud)

您的第二个代码段按预期工作,因为您确实删除了vbCr( Chr(13)) 和vbLf( Chr(10)) 字符。就那么简单。