Base64编码的字符串表示包含某些字符集中的特殊字符的初始字符串,适合此类特殊字符。因此,首先您应该选择要使用的字符集。通常使用 UTF-8 或 UTF-16 即可。我猜你遇到的问题是由 ASCII 引起的。
在下面的示例中,TextBase64Encode函数允许将文本编码为 Base64 并将TextBase64Decode其解码回文本:
Function TextBase64Encode(strText, strCharset)
Dim arrBytes
With CreateObject("ADODB.Stream")
.Type = 2 ' adTypeText
.Open
.Charset = strCharset
.WriteText strText
.Position = 0
.Type = 1 ' adTypeBinary
arrBytes = .Read
.Close
End With
With CreateObject("MSXML2.DOMDocument").createElement("tmp")
.DataType = "bin.base64"
.nodeTypedValue = arrBytes
TextBase64Encode = Replace(Replace(.Text, vbCr, ""), vbLf, "")
End With
End Function
Function TextBase64Decode(strBase64, strCharset)
Dim arrBinary
With CreateObject("MSXML2.DOMDocument").createElement("tmp")
.DataType = "bin.base64"
.Text = strBase64
arrBinary = .nodeTypedValue
End With
With CreateObject("ADODB.Stream")
.Type = 1 ' adTypeBinary
.Open
.Write arrBinary
.Position = 0
.Type = 2 ' adTypeText
.Charset = strCharset
TextBase64Decode = .ReadText
.Close
End With
End Function
Run Code Online (Sandbox Code Playgroud)
为了使它更清楚,我输入了一个示例,其中包含特殊字符,例如单元格中的德语元音变音A2、字符集ASCIIinB2和公式=TextBase64Encode($A$2;B2)in C2。ASCII 表示编码为 Base64 的字符串出现在单元格中C2:
输入公式=TextBase64Decode(C2;B2)来D2解码 Base64:
添加了更多字符集,向下扩展了公式并添加了标题:
现在您可以看到,UTF-8、UTF-16、UTF-7、Windows-1250、latin1 保留了初始样本变音符号,但 ASCII 却被破坏了。有关系统已知的字符集名称的列表,请参阅HKEY_CLASSES_ROOT\MIME\Database\CharsetWindows 注册表中的子项。请注意,UTF-16 LE 编码的字符串通常在开头包含字节 0xFF、0xFE,它们是 Unicode 字节顺序标记 (BOM),而 BOM 的 UTF-8 表示形式是开头的字节 0xEF、0xBB、0xBF。顺便说一句,只需替换bin.base64为bin.hex即可使用十六进制值而不是 Base64。