You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Excel VBA导出JSON文件时如何指定Unicode编码?

解决VBA写入JSON时特殊字符乱码问题

问题根源

你用Open+Print的方式写入文件时,VBA默认采用系统ANSI编码,无法正确保存®、™这类Unicode字符,最终导致这些字符被替换为问号。

可行修复方案

方案1:修正ADODB.Stream代码

你之前的ADODB.Stream代码因缺少关闭流的步骤导致报错,修正后即可正常写入UTF-8编码的文件:

Dim myFile As String
myFile = ThisWorkbook.Path & "/display_data_test.json"

Dim fsT As Object
Set fsT = CreateObject("ADODB.Stream")
With fsT
    .Type = 2 ' 设置为文本模式
    .CharSet = "utf-8" ' 指定UTF-8编码
    .Open
    .WriteText JSON ' 写入JSON字符串
    .SaveToFile myFile, 2 ' 2表示覆盖已有文件
    .Close ' 必须关闭流,避免报错或文件损坏
End With
Set fsT = Nothing ' 释放对象资源

额外注意事项

  • 确保JSON变量本身是VBA的Unicode字符串(直接从Excel单元格读取的文本默认就是Unicode,无需额外处理);
  • 若需要写入无BOM的UTF-8文件(部分工具对BOM敏感),可将代码调整为二进制模式写入:
    Dim myFile As String
    myFile = ThisWorkbook.Path & "/display_data_test.json"
    
    Dim fsT As Object
    Set fsT = CreateObject("ADODB.Stream")
    With fsT
        .Type = 1 ' 二进制模式
        .Open
        .Write StrConv(JSON, vbFromUnicode) ' 转换为UTF-8字节流
        .SaveToFile myFile, 2
        .Close
    End With
    Set fsT = Nothing
    

内容的提问来源于stack exchange,提问作者notAdev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 05:12:13