如果达到一个单元的限制,则在下一个单元中写入Vba

时间:2019-06-23 17:21:48

标签: excel vba

我已经使用VBA创建了CSV到Json转换器。为此,我创建了以下函数:

  If parseAsArrays Then ' Check to see if we need to make our JSON an array; if not, we'll make it an object
    For rowCounter = 1 To rangeToParse.Rows.Count ' Loop through each row
        temp = "" ' Reset temp's value

        For columnCounter = 1 To rangeToParse.Columns.Count ' Loop through each column
            temp = temp & """" & rangeToParse.Cells(rowCounter, columnCounter) & """" & ","
        Next

        temp = "[" & Left(temp, Len(temp) - 1) & "]," ' Remove extra comma from after last object
        parsedData = parsedData & temp ' Add temp to the data we've already parsed
    Next

我的“ parsedData”子目录在这里:

Sub parseData()
Worksheets("Sheet2").Range("b1") = toJSON(getValuesRange("Sheet1"), False) ' Set cell B1's value to our JSON data

结束子

该代码很好用,但有时生成的json对于一个单元格来说太大。因此,如果json对于一个单元格太大,我想创建一个if子句在两个或多个单元格中写入json。有人知道怎么做吗?

1 个答案:

答案 0 :(得分:0)

您可以根据Excel的单元格字符限制(我认为当前为32767)拆分返回的字符串。

尽管您可能想扩展第一个函数只是为了返回一个数组并在此处切出分割字符串函数,因为它要撤消/重复一些初始工作,所以如下所示可能是一个很好的起点。

我使用Cells(Row,Column)在输出列中进行迭代,因为我发现它比偏移更直观。

Sub parseData()

Dim xlCellMaxChar
Dim myRow
Dim myCol
Dim StrArr
Dim ColCounter

myRow = 1
myCol = 2

xlCellMaxChar = 32767
returned_string = toJSON(getValuesRange("Sheet1"), False)

If Len(returned_string) >= xlCellMaxChar Then
    StrArr = SplitString(returned_string, xlCellMaxChar)
    For ColCounter = 0 To UBound(StrArr) - 1
        Worksheets("Sheet2").Cells(myRow, myCol + ColCounter) = StrArr(ColCounter)
    Next
Else
    Worksheets("Sheet2").Cells(myRow, myCol) = returned_string
End If

End Sub

Public Function SplitString(ByVal str As String, ByVal numOfChar As Long) As String()
    Dim sArr() As String
    Dim nCount As Long
    ReDim sArr(Len(str) \ numOfChar)
    Do While Len(str)
        sArr(nCount) = Left$(str, numOfChar)
        str = Mid$(str, numOfChar + 1)
        nCount = nCount + 1
    Loop
    SplitString = sArr
End Function

希望有帮助