0

Let's say I have four data values and one of them exists sometimes.
My For loop crashes because the path doesn't exist.
I would like to pass a "" in the cell instead of crashing.

myJSON.data[i].bank[0].money <- this part is my problem, because the bank[0].money sometimes doesn't exist.
I would like to keep the cell empty.
I tried an If but I didn't get it formatted properly, same goes for error handling.

Sub DATA()
    Set RDict = CreateObject("Scripting.Dictionary")
    Set dlist = CreateObject("Scripting.Dictionary")
    JSON_String = Form.fromURL("exampleurl")
    With CreateObject("htmlfile")
        With .parentWindow
            .execScript "var myJSON = " & JSON_String & ", csvstring = '';for (i = 0; i < myJSON.data.length; i++) {csvstring += myJSON.data[i].name + ',' + myJSON.data[i].bank[0].money + ',' + myJSON.data[i].location + ',' + myJSON.data[i].planneddate + ';';};"
            RData = Split(.csvstring, ";")
        End With
    End With
    For i = 0 To UBound(RData) - 1
        DaData = Split(RData(i), ",")
        If DaData(0) <> "null" Then RDict(DaData(0)) = DaData
    Next i
    Dim RSheet() As Variant
    If RDict.Count > 0 Then
        ReDim RSheet(2 To RDict.Count + 2, 1 To 7)
        i = 0
        For Each D In RDict
            datalist(RDict(Da)(2)) = True
            For j = 0 To 6
                RSheet(i + 2, j + 1) = RDict(Da)(j)
            Next j
            i = i + 1
        Next Da
        RSData.Cells(2, 1).Resize(i, 6) = RSheet
    End If

End Sub
Community
  • 1
  • 1

1 Answers1

0

You can handle null by using optional chaining with default nullish coalescing (#3 in example).

Something like this should work

Change myJSON.data[i]?.bank[0]?.money

To myJSON.data[i]?.bank[0]?.money ?? 'Unknown'

You can do the same with your other variables (myJSON.data[i].location and myJSON.data[i].planneddate) if they have the potential to be undefined or null as well

EDIT - Use Optional IF when optional chaining is not available

If that feature is not available in HTMLDocument's javascript maybe you can use basic conditional if?

This should work for undefined object, because undefined is == null

(myJSON.data[i].bank[0].money != null ? myJSON.data[i].bank[0].money : '-')
dbmitch
  • 5,361
  • 4
  • 24
  • 38