【发布时间】:2021-11-11 07:57:41
【问题描述】:
我有这个代码。它将excel文件转换为json格式。 a, b, c... 是我的标题:
Public Sub json_file()
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Dim fs As Object
Dim jsonfile
Dim rangetoexport As Range
Dim rangetoexport2 As Range
Dim rangetoexport3 As Range
Dim rowcounter As Long
Dim columncounter As Long
Dim linedata As String
Dim rng As Range
Range("A1").Select
Selection.End(xlDown).Select
Dim lRow As Long
lRow = ActiveCell.Row
Set rangetoexport = Sheets(1).Range("A1:N" & lRow)
Set rangetoexport2 = Sheets(1).Range("H1:K" & lRow)
Set rangetoexport3 = Sheets(1).Range("L1:N" & lRow)
Set fs = CreateObject("Scripting.FileSystemObject")
Set jsonfile = fs.CreateTextFile("C:\Users\Desktop\Files\" & "jsondata.txt", True)
linedata = "["
jsonfile.WriteLine linedata
For rowcounter = 2 To rangetoexport.Rows.Count
linedata = ""
For columncounter = 1 To 7
linedata = linedata & """" & rangetoexport.Cells(1, columncounter) & """" & ":" & """" & rangetoexport.Cells(rowcounter, columncounter) & """" & ","
Next
linedata = Left(linedata, Len(linedata) - 1)
For columncounter = 1 To 4
linedata = linedata & """" & rangetoexport2.Cells(1, columncounter) & """" & ":" & "" & rangetoexport2.Cells(rowcounter, columncounter) & "" & ","
Next
linedata = Left(linedata, Len(linedata) - 1)
For columncounter = 1 To 3
linedata = linedata & """" & rangetoexport3.Cells(1, columncounter) & """" & ":" & """" & rangetoexport3.Cells(rowcounter, columncounter) & """" & ","
Next
linedata = Left(linedata, Len(linedata) - 1)
If rowcounter = rangetoexport.Rows.Count Then
linedata = "{" & linedata & "}"
Else
linedata = "{" & linedata & "},"
End If
jsonfile.WriteLine linedata
Next
linedata = "]"
jsonfile.WriteLine linedata
jsonfile.Close
Set fs = Nothing
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
这是一行输出的样子:
{“a”:“1234”,“b”:“0”,“c”:“真”,“d”:“真”,“e”:“1”,“f” : "24", "g": "null" (这里没有逗号)"j": 151.70, "k": 1, "l": 2, "m": true, "n": “空”、“y”:“真”、“z”:“-1”}
我需要它看起来像这样:
{
"a": "1234",
"b": 0,
"c": true,
"d": true,
"e": 1,
"f": 24,
"g": null,
"thresholdValues":
{
"j": 151.70,
"k": 1,
"l": 2,
"m": true
},
"n": null,
"y": true,
"z": -1
}
所以我需要在标题 j 的开头添加 , "thresholdValues": {,在标题 m 的末尾添加 },。有没有办法做到这一点?
【问题讨论】:
-
自从上一个问题stackoverflow.com/questions/69196584/… 以来,您现在是否已将 sheet2 中的数据插入到 sheet1 中
-
是的,我做到了。现在顺序正确,我只需要添加“thresholdValues”:{}
-
H 列的标题是 j 吗?所以标题 A 到 N 是
a,b,c,d,e,f,g,j,k,l,m,n,y,z -
我删除了 h 列。 h 列是阈值。我认为在代码中添加键名“thresholdValues”会更容易:{}
标签: json excel vba for-loop converters