CodexBloom - Programming Q&A Platform

How to correctly implement a VBA function that reads and modifies a JSON file in Excel?

๐Ÿ‘€ Views: 25 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-12
Excel VBA JSON

Could someone explain I'm working on a personal project and I'm trying to create a VBA function in Excel that reads data from a JSON file, modifies that data, and then writes it back to the same file. However, I'm running into issues with the JSON parsing and the writing process. Iโ€™ve been using the `JsonConverter.bas` library for parsing JSON, but I keep getting errors, and I'm not sure if I'm managing file reads and writes correctly. Hereโ€™s a portion of my code: ```vba Sub UpdateJsonFile() Dim jsonFile As String Dim jsonText As String Dim jsonData As Object Dim fso As Object Dim ts As Object jsonFile = "C:\path\to\your\file.json" Set fso = CreateObject("Scripting.FileSystemObject") Set ts = fso.OpenTextFile(jsonFile, 1) ' 1 = ForReading jsonText = ts.ReadAll ts.Close Set jsonData = JsonConverter.ParseJson(jsonText) ' Example modification jsonData("key1") = "new value" ' Writing back to the file Set ts = fso.OpenTextFile(jsonFile, 2) ' 2 = ForWriting ts.Write JsonConverter.ConvertToJson(jsonData) ts.Close End Sub ``` When I run this code, it throws a `Run-time behavior '53': File not found` behavior, even though the path to the JSON file is correct. I've double-checked the file path and made sure that the file exists. Also, Iโ€™m not sure if Iโ€™m correctly converting the JSON object back to a string before writing it. Additionally, is there a best practice for handling file access rights, as I might encounter permission issues on certain systems? Any suggestions on how to properly implement this function or debug the issues Iโ€™m working with would be greatly appreciated. I'm using Excel 2016 on Windows 10. I'm working on a application that needs to handle this. I recently upgraded to Vba 3.9.