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编辑器。

相关推荐
Ada大侦探8 小时前
新手小白学习数据分析03----Excel 报表之大厂周报(2026最新版实操,包教包会!)
学习·数据分析·excel
ID_1800790547312 小时前
企业级实战:淘宝商品详情 API简要说明,json数据返回参考
json
软件富二代15 小时前
— 批量转换Word题库到Excel的小工具
电脑·word·excel·排版·软件
学习3人组17 小时前
业务主表+JSON自定义字段
java·spring boot·json
曦夜日长21 小时前
Linux系统篇,开发工具(二):vim的使用与配置
linux·服务器·vim·excel
金玉满堂@bj1 天前
pytest+uiautomation+allure+Excel 数据驱动桌面自动化
自动化·excel·pytest
Car121 天前
在vscode中添加一个tasks.json实现 rt thread的scons编译功能
vscode·json·build·scons
学习3人组1 天前
基于 主表 + JSON 自定义字段的条件查询
json
XMYX-01 天前
28 - Go JSON 数据操作
开发语言·golang·json
Promise微笑2 天前
Geo专家于磊:Json-LD优化实战SOP与双核四驱体系
大数据·人工智能·重构·json