Excel将单元格中的json本文格式化

打开Excel文件并按下ALT + F11打开Visual Basic for Applications(VBA)编辑器。

输入下面的代码

vbnet 复制代码
Sub FormatJSONCells()
    Dim cell As Range
    Dim jsonString As String
    Dim json As Object
    Dim formattedJSON As String

    ' 循环遍历选定的单元格范围
    For Each cell In Selection
        jsonString = cell.Value
        ' 检查单元格中的内容是否为JSON数据
        If IsValidJSON(jsonString) Then
            ' 使用VBA内置JSON解析功能将JSON数据解析为对象
            Set json = JsonConverter.ParseJson(jsonString)
            ' 将JSON数据重新格式化为易于阅读的形式
            formattedJSON = JsonConverter.ConvertToJson(json, Whitespace:=2)
            ' 将格式化后的JSON数据写回到单元格中
            cell.Value = formattedJSON
        End If
    Next cell
End Sub

Function IsValidJSON(ByVal strJSON As String) As Boolean
    On Error Resume Next
    Dim json As Object
    Set json = JsonConverter.ParseJson(strJSON)
    IsValidJSON = (Err.Number = 0)
    On Error GoTo 0
End Function

进入https://github.com/VBA-tools/VBA-JSON,下载release的最新代码

VBA编辑器,"文件"->"导入", 导入文件 JsonConverter.bas

点击VBA编辑器的菜单栏上的"工具"。

选择"引用",然后在弹出的对话框中找到并勾选"Microsoft Scripting Runtime",以及"Microsoft XML 6.0"。

点击"确定"保存更改。

保存并关闭VBA编辑器。

相关推荐
Frag0ut4 小时前
Notepad++ 零基础入门:从记事本到代码编辑器的平滑过渡(2026最新版)
python·编辑器·html·json·notepad++·markdown·记事本
Data-Miner6 小时前
AI和Excel怎么结合才能真提效
人工智能·excel
xiaoye-duck7 小时前
《C++ 工具库实战》C++ 解析利器 JsonCpp:从基础使用到封装简易 JSON 工具
c++·json·第三方库
javachen__7 小时前
试试Jackson:把JSON拉平成普通属性
json
limanovember1 天前
yq:命令行下的 YAML 和 JSON 处理利器
其他·json
taller_20001 天前
【012】数据类型入门: Excel 数据到 Python 值的转换
python·excel·pie·py
程序员大阳2 天前
副队长JavaScript教程(65)-详解JSON:轻量级数据交换格式
javascript·json·序列化·反序列化·stringify·parse
光影6273 天前
Unittest单元测试基础速记
测试工具·单元测试·json·测试覆盖率
ZLongTeng3 天前
EIDE的launch.json文件
json
梦想不只是梦与想3 天前
Python 中的 json 模块
python·json·对象转字符串