我对Outlook VBA宏在一行中显示字符串有问题。目的是覆盖现有的电子邮件正文(带有一些HTML标记,但是为了简单起见,下面没有显示)。因此,假设我们有一个字符串,例如objItem.Body中的110个字符。 问题在于,下面的代码会自动将字符串分成两行(我希望将其分成一行)!
Dim strSource As String
Dim aryLines() As String
Dim temp As String
strSource = objItem.Body
aryLines = Split(strSource, vbCrLf)
For i = LBound(aryLines) To UBound(aryLines)
temp = temp & aryLines(i)
Next i
objItem.HTMLBody = temp
我在哪里弄错了?
答案 0 :(得分:0)
您的问题在于如何重新组装/连接变量temp
。当您遍历数组aryLines()
时,您从未添加换行符。考虑下面的代码:
Sub oneLineText()
Dim strSource As String
Dim aryLines() As String
Dim temp As String
strSource = "The dog jumped over the fence"
aryLines() = Split(strSource, " ")
For Each ele in aryLines
temp = temp & ele & " "
next ele
End Sub
结果将与源相同。现在,考虑以下几点:
Sub multiLineText()
Dim strSource As String
Dim aryLines() As String
Dim temp As String
strSource = "The dog jumped over the fence"
aryLines() = Split(strSource, " ")
For Each ele in aryLines
temp = temp & ele & vbNewLine
next ele
End Sub
这将导致每行在换行符上包含ele
变量。另外,您可以使用For Each
而不是使用For i = LBound(array) to UBound(array)
遍历变量。每次循环迭代时,都必须执行计算LBound()
和UBound()
。根据循环的大小,这可能会导致相当大的处理开销,但是在较短的循环中,成本可以忽略不计。
编辑:更改了一个oneLineText(),使其包含基于FreeMan注释的空格。
答案 1 :(得分:0)
目标是将字符串放入HTML标记中,但是在进行主体重写时,由于某种原因,字符串会分成两行,并且字符串长度超过78个字符。 – AndrewBee
答案 2 :(得分:0)
我看了问题的editions。因此,我假设VbCrLf
中有一些objItem.Body
。
因此,使用Original
可以正确分割结果,并且ShouldWork
返回一行,因为分割是由VbCrLf
完成的,因此不再重复:
Sub TestMe()
Dim someInput As String
someInput = "Sumarum: 531 - Item1 - Item2 - Item3-4. - Item5 - " & vbCrLf & _
" - Item6 - Item7 - Item8 - Item9 Item10 - Item6 - -"
Debug.Print Original(someInput)
Debug.Print ShouldWork(someInput)
Debug.Print Original(someInput) = ShouldWork(someInput)
End Sub
Public Function ShouldWork(someInput As String) As String
Dim strSource As String
Dim aryLines() As String
Dim temp As String, i As Long
strSource = someInput
aryLines = Split(strSource, vbCrLf)
For i = LBound(aryLines) To UBound(aryLines)
temp = temp & aryLines(i)
Next i
ShouldWork = temp
End Function
Public Function Original(someInput As String) As String
Dim arr() As String
Dim tt As String: tt = someInput
Dim temp As String
arr = Split(tt, ":")
temp = temp & arr(0) & ": " & arr(1)
Original = temp
End Function
这是我在即时窗口中看到的: