excel JSON函数,用于将标题行作为第一行,将数据区域作为单行

ktca8awb  于 2022-12-14  发布在  其他
关注(0)|答案(1)|浏览(140)

我有这个代码,它将任何命名的范围转换为一个json字符串。但考虑选定范围的第一行作为标题。我想要的是,我的excel工作表的第一行总是作为标题(固定)和任何行/行选择作为一个范围被转换为一个json与标题从第一个固定行

' Check there must be at least two columns in the Excel file
    If rng.Columns.Count < 2 Then
        ExcelToJSON = CVErr(xlErrNA)
        Exit Function
    End If
    Dim dataLoop, headerLoop As Long
    ' Get the first row of the Excel file as a header
    Dim headerRange As Range: Set headerRange = Sheet1.Range(rng.Rows(1).Address)
    ' Count the number of columns of targeted Excel file
    Dim colCount As Long: colCount = headerRange.Columns.Count
    Dim JSON As String: JSON = "["
    For dataLoop = 1 To rng.Rows.Count
        ' Skip the first row of the Excel file because it is used as header
        If dataLoop > 1 Then
            ' Start data row
            Dim jsonData As String: jsonData = "{"
            ' Loop through each column and combine with the header
            For headerLoop = 1 To colCount
                jsonData = jsonData & """" & headerRange.Value2(1, headerLoop) & """" & ":"
                jsonData = jsonData & """" & rng.Value2(dataLoop, headerLoop) & """"
                jsonData = jsonData & ","
            Next headerLoop
            ' Strip out the comma in last value of each row
            jsonData = Left(jsonData, Len(jsonData) - 1)
            ' End data row
            JSON = JSON & jsonData & "},"
        End If
    Next
    ' Strip out the last comma in last row of the Excel data
    JSON = Left(JSON, Len(JSON) - 1)
    JSON = JSON & "]"
    ExcelToJSON = JSON
End Function
i2byvkas

i2byvkas1#

将值的指定变更为headerRange,即

Set headerRange = Sheet1.Cells(1, rng.Column).Resize(1, rng.Columns.Count)

然后注解掉下面的行

If dataLoop > 1 Then

及其相应的

End If

得双曲余切值.
(btw您的dataLoop变量为Variant类型,因为在同一行声明多个变量时,必须在 each 变量后指定数据类型)

相关问题