为什么 VBA 替换函数不能与 Word 和 Excel 中的 CRLF 一起使用 [英] Why Doesn't VBA replace function work with CRLF in Word and Excel
问题描述
我可以发誓我过去已经剥离了 CRLF,但不确定为什么以下不起作用:
I could have sworn I have stripped CRLF in the past but not sure why the following isn't working:
myString = "ABC" & vbCrLf & "DEF"
str1 = Replace(myString, vbLf, "")
str2 = Replace(str1, vbCrLf, "")
str3 = Replace(str2, vbNewLine, "")
MsgBox str3
上面的代码不起作用,结果是:
The code above doesn't work the result is:
ABC
DEF
<小时>
myString = "ABC" & vbCrLf & "DEF"
str1 = Replace(myString, Chr(13), "")
str2 = Replace(str1, Chr(10), "")
MsgBox str2
上面的代码确实有效,结果是:
The code above does work the result is:
ABCDEF
解决方案:感谢@ Mat 的回答(第一个代码的问题是我试图删除项目的顺序)VbCrLf &VbNewLine 是相同的,在删除 VbLf 后尝试删除组合 vbCr+VbLf 将不起作用
Solution: Thanks @ Mat for the answer (The problem on the first code was the order I was trying to remove the items) VbCrLf & VbNewLine is the same and trying to remove the combo vbCr+VbLf after removing VbLf won't work
推荐答案
前提有缺陷:
myString = "ABC" & vbCrLf & "DEF"
字符串由ABC"、vbCrLf
和DEF"组成.
The string is made of "ABC", vbCrLf
, and "DEF".
vbCrLf
是 vbCr
和 vbLf
,在任何 Windows 机器上都是 vbNewLine
.
vbCrLf
is vbCr
and vbLf
, which on any Windows box is vbNewLine
.
当你这样做时:
str1 = Replace(myString, vbLf, "")
您替换 vbLf
并保留 vbCr
字符.
str2 = Replace(str1, vbCrLf, "")
然后您替换 vbCrLf
但是 vbLf
已经消失,所以 vbCrLf
不在字符串中.
Then you replace vbCrLf
but vbLf
is already gone so vbCrLf
isn't in the string.
str3 = Replace(str2, vbNewLine, "")
然后你替换 vbNewLine
,它基本上和前面的指令做完全一样的事情,结果是一个字符串被去除了 vbLf
但仍然包含 vbCr
.
Then you replace vbNewLine
which is basically doing the exact same thing as the previous instruction, and the result is a string that's been stripped of vbLf
but still contains vbCr
.
此代码按预期工作:
Sub Test()
Dim foo As String
foo = "foo" & vbCrLf & "bar"
Debug.Print foo
foo = Replace(foo, vbNewLine, vbNullString)
Debug.Print foo
End Sub
就像这样:
Sub Test()
Dim foo As String
foo = "foo" & vbNewLine & "bar"
Debug.Print foo
foo = Replace(foo, vbNewLine, vbNullString)
Debug.Print foo
End Sub
或者这个:
Sub Test()
Dim foo As String
foo = "foo" & vbNewLine & "bar"
Debug.Print foo
foo = Replace(foo, vbCrLf, vbNullString)
Debug.Print foo
End Sub
甚至这个:
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
<小时>
您的第二个代码段按预期工作,因为您do删除了 vbCr
(Chr(13)
) 和 vbLf
(Chr(10)
) 个字符.就这么简单.
Your second snippet works as intended, because you do remove both vbCr
(Chr(13)
) and vbLf
(Chr(10)
) characters. Simple as that.
这篇关于为什么 VBA 替换函数不能与 Word 和 Excel 中的 CRLF 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!