VBA 与 & 的连接导致问题,因为字符串也有 &

VBA concatenation with & cause issues as string also has &

我正在从一个单元格中读取一个值,其中的内容包含 & 作为字符串的一部分。例如单元格值为 "BAU Dev & Production Support-Partner"

xCellValue = xRg.Cells(i, 2).Value
xMsg = " This is a test of the concatenation "
xMsg = xMsg & xCellValue & vbCrLf & vbCrLf

当我打印 xCellValue 时,它​​显示 "This is a test of the concatenation BAU Dev"。

因此,单元格内的 & 已成为串联的一部分。我如何告诉 VBA 不要解释单元格内的 &?

感谢所有回复的人。我 Debug.Print 并进一步确定了问题:

    xURL = "mailto:" & xEmail & "?subject=" & xSubj & "&body=" & xMsg
    Debug.Print xURL
    ShellExecute 0, vbNullString, xURL, vbNullString, vbNullString, vbNormalFocus

直到 Debug.Print xURL,& 仍显示在字符串中。但是,字符串在 ShellExecute xMsg 中的 & 之后终止。问题不在于我之前认为的读取单元格值。如果我设置

xMsg = " This is a test & of the concatenation "

ShellExecute 中的正文消息只会显示“This is a test”

好的,我找到了解决方案。我需要

' Replace & with %26 (hex)
xMsg = Application.WorksheetFunction.Substitute(xMsg, "&", "%26")

这也是我需要的原因

' Replace spaces with %20 (hex)
xSubj = Application.WorksheetFunction.Substitute(xSubj, " ", "%20")
xMsg = Application.WorksheetFunction.Substitute(xMsg, " ", "%20")
' Replace carriage returns with %0D%0A (hex)
xMsg = Application.WorksheetFunction.Substitute(xMsg, vbCrLf, "%0D%0A")

更多详情,请查看URL encoding