VBA 对 Unicode 的支持并不是那么好。
可以处理 Unicode 字符串,但您将无法看到实际的字符Debug.Print
or MsgBox
- 他们将显示为?
there.
您可以设置控制面板 > 区域和语言 > 管理选项卡 >“非 Unicode 程序的当前语言”到“俄语”切换到不同的代码页,这将允许您在 VBA 消息框中看到西里尔字母而不是问号。但这只是表面上的改变。
你真正的问题是别的。
服务器 (nfs.mobile.bg) 将文档发送为Content-Type: text/html
。没有关于字符编码的信息。这意味着接收者必须自己找出字符编码。
浏览器通过查看响应字节流并进行猜测来做到这一点。对于你的情况,一个有帮助的<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
标签存在于 HTML 源代码中。因此,字节流应该解释为Windows-1251
,这恰好是 Windows 中的西里尔字母 ANSI 代码页。
所以,我们这里甚至没有 Unicode!
在没有任何附加信息的情况下,responseText
的财产XMLHTTP
对象默认为us-ascii
。西里尔字母表中的扩展字符不存在于 ASCII 中,因此它们将被转换为actual问号并丢失。这就是为什么你不能使用responseText
为了任何东西。
但是,那original响应的字节仍然可用,在responseBody
属性,它是一个数组Byte
.
在 VBA 中,您必须执行与浏览器相同的操作。您必须将字节流解释为特定的字符集。这ADODB.Stream
object 可以为你做到这一点,而且也非常简单:
' reference: "Microsoft XML, v6.0" (or any other version)
' reference: "Microsoft ActiveX Data Objects 6.1 library" (or any other version)
Option Explicit
Sub HTMLsearch()
Dim url As String, html As String
url = "http://nfs.mobile.bg/pcgi/mobile.cgi?act=3&slink=6jkjov&f1=1"
html = GetHTML(url, "Windows-1251")
' Cyrillic characters are supported in Office, so they will appear correctly
ActiveDocument.Range.InsertAfter html
End Sub
Function GetHTML(Url As String, Optional Charset As String = "UTF-8") As String
Dim request As New MSXML2.XMLHTTP
Dim converter As New ADODB.stream
' fetch page
request.Open "GET", Url, False
request.send
' write raw bytes to the stream
converter.Open
converter.Type = adTypeBinary
converter.Write request.responseBody
' switch the stream to text mode and set charset
converter.Position = 0
converter.Type = adTypeText
converter.Charset = Charset
' read text characters from the stream, close the stream
GetHTML = converter.ReadText
converter.Close
End Function
我一直在这里使用 MS Word 并打电话HTMLsearch()
正确地将西里尔字符写入页面。他们仍然看起来像?
in a MsgBox
但对我来说,这纯粹是一个显示问题,是由 VBA 创建的 UI 无法处理 Unicode 造成的。